在我们ftp登录时都会出现一个如图所示的提示框,这个功能可以通过配置我们的文件进行实现,而不需要写任何的代码。
一、修改角色(添加、删除)
conf/tomcat-users.xml存放tomcat的角色,默认有admin、manager等角色,如果想要添加自定义的角色,可以通过形如
<user username="xiazdong" password="xiazdong" roles="user"/>形式,我们现在配置了一个名字为xiazdong,密码是xiazdong,角色是user的用户。
如果重启tomcat,在tomcat-users.xml中会自动生成一个<role rolename="user"/>的语句。
二、实现登录验证
在WEB-INF/web.xml中需要写入形如
- <security-constraint>
- <web-resource-collection>
- <web-resource-name>RegisterUsers</web-resource-name>
- <url-pattern>/demo/security.jsp</url-pattern> <!-- 验证的网页的位置-->
- </web-resource-collection>
- <auth-constraint>
- <role-name>user</role-name> <!-- 验证的角色,别写成用户名-->
- </auth-constraint>
- </security-constraint>
- <login-config>
- <auth-method>BASIC</auth-method> <!-- 关键-->
- <realm-name>Registered Users</realm-name>
- </login-config>
- <security-role>
- <role-name>user</role-name> <!-- 验证的角色,别写成用户名-->
- </security-role>
重启tomcat,则可以写一个security.jsp验证一下。
输入用户名为xiazdong,密码是xiazdong即可登录网页。
如果角色是user的话,则能够看到网页。
- <%@ page contentType="text/html" language="java" pageEncoding="GB2312"%>
- <html>
- <head>
- <title>title</title>
- </head>
- <body>
- <%
- if(request.isUserInRole("user")){
- out.println("Hello world");
- }
-
- %>
-
- </body>
- </html>
|