1. 基于Session的安全认证方式
- 描述:当我们没有进行安全认证的时候,直接在浏览器地址栏输入http://127.0.0.1:8080/Security_Session/index.jsp会直接访问页面,这是我们不希望看到的。我们希望index.jsp页面是我们管理员角色才能访问的,因此需要进行一个安全认证。
- 原理:借助session机制,我们将用户的角色信息记录在session中,在页面对session中的角色进行认证,如果是admin角色则允许访问index.jsp页面,否则重定向到login.jsp页面进行登录。
- 工具:IDEA2018 + Tomcat8.0
- 技术:Servlet + session
- 项目:Security_Session
2. login.jsp
<%--
@Description 系统登录页面
@Author 周威
@Date 2020-07-04 - 11:25
--%>
<%@ page language="java" contentType="text/html;charset=utf-8" %>
<html>
<head>
<title>登录</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="author" content="周威"/>
</head>
<body>
<div>
<h2>------------Welcome To Login Page---------</h2>
<form action="${ pageContext.request.contextPath }/UserServlet.do" method="post">
<p>UserName:<input name="username" type="text"></p>
<p>PassWord:<input name="password" type="password"></p>
<p><input type="submit" value="登录"></p>
</form>
</div>
</body>
</html>
3. index.jsp
<%--
@Description 系统首页
@Author 周威
@Date 2020-07-04 - 11:22
--%>
<%@ page language="java" contentType="text/html;charset=utf-8" %>
<html>
<head>
<title>系统首页</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<meta name="author" content="周威"/>
<%
//1.取出Session中的角色信息
String role = (String) session.getAttribute("role");
//2.进行角色信息权限认证,如果用户角色不是admin不允许访问该页面,重定向到登录页面
if(role == null || !"admin".equals(role))
response.sendRedirect("./login.jsp");
%>
</head>
<body>
Welcome ${ sessionScope.userName }
</body>
</html>
4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"