Filter filter to verify whether the user is logged in

Personal blog
In order to protect information security and prevent direct access to information pages, you need to verify whether the user is logged in. The idea is to first filter out the path of the resources included in the login function, and determine whether the user is logged in when accessing other resources-to determine whether the Session contains User. Let go if you have it, and jump to the landing page if not.
Insert picture description here

@WebFilter("/*")
public class LoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //强制转化
        HttpServletRequest request = (HttpServletRequest) req;
        //获取资源请求路径
        String uri = request.getRequestURI();
        //判断是否包含登陆相关资源路径,注意排除掉css/js/图片/验证码等资源
        if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/js/")
                || uri.contains("/css/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet")){
            //包含登陆资源路径则放行
            chain.doFilter(req, resp);
        }else {
            //不包含,需要判断用户是否已登陆
            //从session中获取user
            Object user = request.getSession().getAttribute("user");
            if (user != null){
                chain.doFilter(req, resp);
            }else {
                request.setAttribute("login_msg","您尚未登陆,请登录");
                request.getRequestDispatcher("/login.jsp").forward(request,resp);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

}
   public void destroy() {
    }

}
Published 28 original articles · praised 0 · visits 722

Guess you like

Origin blog.csdn.net/William_GJIN/article/details/105017168