package com.itheima.web.Filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; /* * 登陆验证的过滤器 * */ @WebFilter("/*") public class LoginFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { //先把接收到的req强转成HttpServletRequest格式的,不然获取不了Session对象 HttpServletRequest request = (HttpServletRequest) req; //判断访问资源路径是否和登录注册相关 String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/registerServlet","/register.jsp","/checkCodeServlet"}; //获取当前路径资源 String url = request.getRequestURL().toString(); //循环判断 for (String u : urls) { if (url.contains(u)){//contains包含 //找到了 //放行 chain.doFilter(req,resp); //结束方法 return; } } //1. 获取到session对象中的user数据 HttpSession session = request.getSession(); Object user = session.getAttribute("user"); //2. 判断session中是否有user if (user != null){ //登录过了 //放行 }else { //没有登录,储存提示信息,跳转到登录页面 request.setAttribute("login_msg","您尚未登陆!"); request.getRequestDispatcher("/login.jsp").forward(req,resp); } //放行 chain.doFilter(req, resp); } public void destroy() { } public void init(FilterConfig config) throws ServletException { } }
标签:登录,验证,resp,req,request,Filter,user,import From: https://www.cnblogs.com/Karl-hut/p/17522745.html