前提:两个页面login.html 和 index.html
要求:实现登录过滤,即只有登录成功才可以跳转到index.html
思路:登录成功时,在后端将该用户的信息存于Session中(暂且命名为user),然后定义过滤器。因为Session的生命周期是从打开浏览器到关闭浏览器,所以过滤的条件可以设置为如果Session中的user不为空,则放行继续项目流程。反之则重定向到login.html
LoginController 登陆成功将用户信息保存于Session中
定义过滤器 我们首先要知道过滤器什么时候执行,如下图所示
为了防止不登录通过url请求的方式直接跳转到index.html,在此设置判断条件为如果url结尾为index.html且Session中的user为空,则重定向到登录界面
package com.hospital.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AccessControlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request =(HttpServletRequest) servletRequest;
HttpServletResponse response=(HttpServletResponse) servletResponse;
String requestURI =request.getRequestURI();
HttpSession session = request.getSession();
Object users=session.getAttribute("user");
if (requestURI.endsWith("index.html")&&users==null){
response.sendRedirect("/pages/login.html");
}
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
在web.xml中注册过滤器
<filter>
<filter-name>AccessControlFilter</filter-name>
<filter-class>
com.hospital.filter.AccessControlFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>AccessControlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
|