在web應(yīng)用中,對頁面的訪問控制通常通過程序來控制,流程為:
登錄 -> 設(shè)置session -> 訪問受限頁面時檢查session是否存在,如果不存在,禁止訪問
對于較小型的web應(yīng)用,可以通過tomcat內(nèi)置的訪問控制機制來實現(xiàn)權(quán)限控制。采用這種機制的好處是,程序中無需進行權(quán)限控制,完全通過對tomcat的配置即可完成訪問控制。
為了在tomcat頁面設(shè)置訪問權(quán)限控制,在項目的WEB-INFO/web.xml文件中,進行如下設(shè)置:
<web-app>
<!--servlet等其他配置-->
<security-constraint>
<web-resource-collection>
<display-name>Example Security Constraint</display-name>
<web-resource-name>My Test</web-resource-name>
<url-pattern>/ddly/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>role1</role-name>
<role-name>tomcat</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>My Test</realm-name>
</login-config>
</web-app>
其中,<url-pattern>中指定受限的url,可以使用通配符*,通常對整個目錄進行訪問權(quán)限控制。
<auth-constraint>中指定哪些角色可以訪問<url-pattern>指定的url,在<role-name>中可以設(shè)置一個或多個角色名。
使用的角色名來自tomcat的配置文件${CATALINA_HOME}/conf/tomcat-users.xml。
<login-config>中設(shè)置登錄方式,<auth-method>的取值為BASIC或FORM。如果為BASIC,瀏覽器在需要登錄時彈出一個登錄窗口。如果為FORM方式,需要指定登錄頁面和登錄失敗時的提示信息顯示頁面。
使用FORM方式的配置樣例如下:
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Example Form-Based Authentication Area</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
其中的<form-login-page>指定登錄頁面url,<form-error-page>指定登錄失敗時的提示頁面url。
登錄頁面中,form的action,以及其中的用戶名和密碼兩個參數(shù)的名稱,都應(yīng)取固定的值。登錄的后臺處理程序為j_security_check;用戶名和密碼的參數(shù)名稱分別為:j_username和j_password。
如下是登錄頁面(如:login.jsp)的一段示例代碼:
<form method="POST" action='<%= response.encodeURL("j_security_check") %>' >
<table border="0" cellspacing="5">
<tr>
<th align="right">Username:</th>
<td align="left"><input type="text" name="j_username"></td>
</tr>
<tr>
<th align="right">Password:</th>
<td align="left"><input type="password" name="j_password"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Log In"></td>
<td align="left"><input type="reset"></td>
</tr>
</table>
</form>