<login-config><auth-method>BASIC</auth-method></login-config>
在web應用中,要經常對用戶的身份進行驗證的,但其實TOMCAT下配合SERVLET的話,也可以實現一些簡單的驗證,以往
可能大家都會忽略之,現再簡單總結學習之。
1、BASIC驗證機制
這有點象WINDOWS集成驗證機制,就是驗證時彈出一個窗口,要你輸入用戶名和密碼。做法如下
首先建立在webapps下建立目錄member,下面放一個需要假設要權限才能查看的頁面test.html,
然後在tomcat的\conf目錄下找到tomcat-users.xml文件,在其中增加
<user username="test" password="test" roles="member"/>
這裏我們定義了角色member
然後再在web.xml裏,如下定義
- <web-app>
- <security-constraint>
- <web-resource-collection>
- <web-resource-name>
- Member Area
- </web-resource-name>
- <description>
- Only registered members can access this area.
- </description>
- <url-pattern>/member/*</url-pattern>
- <http-method>GET</http-method>
- <http-method>POST</http-method>
- </web-resource-collection>
- <auth-constraint>
- <role-name>member</role-name>
- </auth-constraint>
- </security-constraint>
- <login-config>
- <auth-method>BASIC</auth-method>
- </login-config>
- <security-role>
- <role-name>member</role-name>
- </security-role>
- </web-app>
這裏用<login-config>
<auth-method>BASIC</auth-method>
</login-config>
指出採用basic驗證方式,並指出了對於訪問/member/*下的文件時,都需要獲得 member角色的授權。
2、form表單驗證
這裏首先搞一個要輸入用戶名和密碼的頁面a.html,再搞一個當出錯時顯示的頁面error.html,注意用戶名和密碼的文本框的設計中,
要規定name='j_username' name='j_password',,並要設定<form action='j_security_check' method='POST'>
然後在tomcat-users.html中設定用戶帳號member(同上),web.xml設定如下
- <web-app>
- <security-constraint>
- <web-resource-collection>
- <web-resource-name>
- Member Area
- </web-resource-name>
- <description>
- Only registered members can access this area.
- </description>
- <url-pattern>/member/*</url-pattern>
- <http-method>GET</http-method>
- <http-method>POST</http-method>
- </web-resource-collection>
- <auth-constraint>
- <role-name>member</role-name>
- </auth-constraint>
- </security-constraint>
- <login-config>
- <auth-method>FORM</auth-method>
- <form-login-config>
- <form-login-page>/login/a.html
- </form-login-page>
- <form-error-page>/login/error.html
- </form-error-page>
- </form-login-config>
- </login-config>
- <security-role>
- <role-name>member</role-name>
- </security-role>
- </web-app>