<login-config><auth-method>BASIC</auth-method></login-config>

<login-config><auth-method>BASIC</auth-method></login-config>

web實現basic與FORM驗證 
在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裏,如下定義 
 
Xml代碼    收藏代碼
  1. <web-app>  
  2. <security-constraint>  
  3.   <web-resource-collection>  
  4.      <web-resource-name>  
  5.         Member Area  
  6.      </web-resource-name>  
  7.      <description>  
  8.         Only registered members can access this area.  
  9.      </description>  
  10.      <url-pattern>/member/*</url-pattern>  
  11.      <http-method>GET</http-method>  
  12.      <http-method>POST</http-method>  
  13.   </web-resource-collection>  
  14.   <auth-constraint>  
  15.      <role-name>member</role-name>  
  16.   </auth-constraint>  
  17. </security-constraint>  
  18. <login-config>  
  19.   <auth-method>BASIC</auth-method>  
  20. </login-config>  
  21. <security-role>  
  22.   <role-name>member</role-name>  
  23. </security-role>  
  24. </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設定如下 
Xml代碼    收藏代碼
  1. <web-app>  
  2. <security-constraint>  
  3.   <web-resource-collection>  
  4.      <web-resource-name>  
  5.         Member Area  
  6.      </web-resource-name>  
  7.      <description>  
  8.         Only registered members can access this area.  
  9.      </description>  
  10.      <url-pattern>/member/*</url-pattern>  
  11.      <http-method>GET</http-method>  
  12.      <http-method>POST</http-method>  
  13.   </web-resource-collection>  
  14.   <auth-constraint>  
  15.      <role-name>member</role-name>  
  16.   </auth-constraint>  
  17. </security-constraint>  
  18. <login-config>  
  19.   <auth-method>FORM</auth-method>  
  20.   <form-login-config>  
  21.      <form-login-page>/login/a.html  
  22.      </form-login-page>  
  23.      <form-error-page>/login/error.html  
  24.      </form-error-page>  
  25.   </form-login-config>  
  26. </login-config>  
  27. <security-role>  
  28.   <role-name>member</role-name>  
  29. </security-role>  
  30. </web-app>  
最後設定web.xml 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章