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里,如下定义
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设定如下
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