在web應(yīng)用中,要經(jīng)常對(duì)用戶的身份進(jìn)行驗(yàn)證的,但其實(shí)TOMCAT下配合SERVLET的話,也可以實(shí)現(xiàn)一些簡(jiǎn)單的驗(yàn)證,以往
可能大家都會(huì)忽略之,現(xiàn)再簡(jiǎn)單總結(jié)學(xué)習(xí)之。
1、BASIC驗(yàn)證機(jī)制
???? 這有點(diǎn)象WINDOWS集成驗(yàn)證機(jī)制,就是驗(yàn)證時(shí)彈出一個(gè)窗口,要你輸入用戶名和密碼。做法如下
???? 首先建立在webapps下建立目錄member,下面放一個(gè)需要假設(shè)要權(quán)限才能查看的頁面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驗(yàn)證方式,并指出了對(duì)于訪問/member/*下的文件時(shí),都需要獲得 member角色的授權(quán)。
2、form表單驗(yàn)證
???? 這里首先搞一個(gè)要輸入用戶名和密碼的頁面a.html,再搞一個(gè)當(dāng)出錯(cuò)時(shí)顯示的頁面error.html,注意用戶名和密碼的文本框的設(shè)計(jì)中,
要規(guī)定name='j_username'? name='j_password',,并要設(shè)定<form action='j_security_check' method='POST'>
然后在tomcat-users.html中設(shè)定用戶帳號(hào)member(同上),web.xml設(shè)定如下
<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>
最后設(shè)定web.xml
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

