http://www.ietf.org/rfc/rfc2617.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
<?xml version="1.0" encoding="utf-8"?> <web-app 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_3_0.xsd" version="3.0"> <security-constraint> <web-resource-collection> <web-resource-name>JSP pages</web-resource-name> <url-pattern>*.jsp</url-pattern> </web-resource-collection> <auth-constraint /> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Servlet1</web-resource-name> <url-pattern>/servlet1</url-pattern> </web-resource-collection> <auth-constraint> <role-name>member</role-name> <role-name>manager</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>Members Only</realm-name> </login-config> </web-app>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
package servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet( urlPatterns = {"/servlet1"} ) @ServletSecurity( @HttpConstraint( rolesAllowed = "manager" ) ) public class Servlet1 extends HttpServlet { private static final long serialVersionUID = 119L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { RequestDispatcher dispatcher = request .getRequestDispatcher("/jsp/1.jsp"); dispatcher.forward(request, response); } }
|
1 2 3 4 5 6 7 8 9
|
<!DOCTYPE HTML> <html> <head> <title>Welcome</title> </head> <body> <h2>Hello World</h2> </body> </html>
|
http://localhost:8080/app12b/servlet1
此时,浏览器中不会显示
Servlet1
的输出,而是要求输入用户名(tom)和密码(tom),如下图所示:
用户名和密码需要在
Tomcat
安装目录下的
conf
目录下的
tomcat-users.xml
中配置,详情请看:
12.1 身份验证和授权
小节中.
现在输入
tomcat-user.xml
中配置过的用户名
tom
,密码
tom
,就可以访问这个
Servlet1
了,显示效果如下图所示:
认证过后,再次点击上述链接则可以直接访问
Servlet1
,不再需要重复认证.
http://localhost:8080/app12c/servlet1
输入正确的用户名
tom
,密码
tom
:
然后才可以访问
Servlet1
,浏览器显示效果如下:
原文链接:
12.2 身份验证方法