Tomcat下的JAAS实例

创建文件login.jsp和error.jsp

login.jsp的代码如下

<html> <head> <meta HTTP-EQUIV="Content-Type" Content="text-html; charset=gbk"> <title>login</title> </head> <body> <form method="POST" action="j_security_check"> 姓名:<input type="text" name="j_username"/><br/> 密码:<input type="password" name="j_password"/><br/> <input type="submit" value="提交"/> </form> </body> </html> error.jsp的代码如下

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>错误页面</title> </head> <body> <center><h1><font color="gray">页面发生错误</font></h1></center> </body> </html> 创建一个文件index.jsp

index.jsp代码如下

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>主页</title> </head> <body bgcolor="#FFFFFF"> request.FORM_AUTH:<%=request.FORM_AUTH%><br/> request.getRemoteUser():<%=request.getRemoteUser()%><br/> </body> </html> 设置配置文件

web.xml的代码如下

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <security-constraint> <web-resource-collection> <web-resource-name>protected-resource</web-resource-name> <url-pattern>/*</url-pattern> <http-method>HEAD</http-method> <http-method>GET</http-method> <http-method>POST</http-method> <http-method>PUT</http-method> <http-method>DELETE</http-method> </web-resource-collection> <auth-constraint> <role-name>role1</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/error.jsp</form-error-page> </form-login-config> </login-config> <security-role> <description>Role1</description> <role-name>role1</role-name> </security-role> </web-app> 打开tomcat目录下的conf/tomcat-users.xml文件,如下内容

<?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="tomcat"/> <role rolename="role1"/> <user username="tomcat" password="tomcat" roles="tomcat"/> <user username="role1" password="tomcat" roles="role1"/> <user username="both" password="tomcat" roles="tomcat,role1"/> </tomcat-users>

启动tomcat,在浏览器中输入地址http://localhost:8080/JAASPrj/,显示的内容不是/web/index.html,而是login.jsp的内容,输入both或者role1的用户名和密码,将会看到web/index.html的内容,当然,如果输入错误,则会提示错误信息。验证通过后,我们可以看到如下内容:

request.FORM_AUTH:FORM

request.getRemoteUser():both //用户名


你可能感兴趣的:(html,tomcat,user,input,import,encoding)