在web应用中,要经常对用户的身份进行验证的,但其实TOMCAT下配合SERVLET的话,也可以实现一些简单的验证,以往 可能大家都会忽略之,现再简单总结学习之。
这有点象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角色的授权。
这里首先搞一个要输入用户名和密码的页面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
发表评论(对文章涉及的知识点还有疑问,可以在这里留言,老高看到后会及时回复的。)