在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>
最后設定web.xml
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
