Tomcat安全验证实例步骤:
(1)在Web应用的web.xml中加入security constraint。 <security-constraint> <web-resource-collection> <web-resource-name>Constraint</web-resource-name> <!—受保护的资源的url-pattern--> <url-pattern>/jsp/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>admin</role-name> </security-role> <login-config> <!—验证方法:BASIC,Digest,Form--> <auth-method>FORM</auth-method> <realm-name>Constraint</realm-name> <form-login-config> <!--一下是分别处理处理登录和错误的页面--> <form-login-page>/jsp/login.jsp</form-login-page> <form-error-page>/jsp/error.jsp</form-error-page> </form-login-config> </login-config> (2)写一个登录页面login.jsp(j_username,j_password,j_security_check是固定的)和错误页面error.jsp login.jsp: <html> <body> <head> <title>Login</title> </head> <body> <form name="loginForm" method="POST" action="j_security_check"> <input name="j_username" type="text"> <input name="j_password" type="password"> <input name="submit" type="submit"> </form> </body> </html> error.jsp: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <%out.print("Error!"); %> </body> </html> (1) 修改tomcat-users.xml,加入想要控制的角色和用户。例如role:admin user:wangpeng password:123456 (2) 在server.xml中加入<Realm className="org.apache.catalina.realm.MemoryRealm"/>,不过好像不改也可以。 键入http://localhst:8080/TestAuth/jsp/index.jsp,系统会自动跳到login.jsp,输入wangpeng/123456,系统再转回index.jsp,否则转到错误页面。