public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //拦截功能启动提示 System.out.println("===============过滤拦截功能启动=============="); //强转收发类型 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse rep = (HttpServletResponse) response; //过滤页面提示 System.out.println("过滤链接url:" + req.getRequestURI()); System.out.println("过滤方法(GET/POST)method:" + req.getMethod()); //判断过滤放行(static/*下所有文件)方法 if (req.getRequestURI().startsWith(req.getContextPath() + "/static/")) { System.out.println("过滤放行/static/*下所有文件"); chain.doFilter(request, response); return; } //判断过滤放行login登录页面 if (req.getRequestURI().equals(req.getContextPath() + "/login")) { System.out.println("过滤放行/login登录页面"); chain.doFilter(request, response); return; } //判断过滤放行validateimage二维码页面 if (req.getRequestURI().equals(req.getContextPath() + "/validateimage")) { System.out.println("过滤放行/validateimage二维码"); chain.doFilter(request, response); return; } //判断过滤放行POST提交方法 if (req.getMethod().equals("POST")) { System.out.println("过滤放行POST提交方法"); chain.doFilter(request, response); return; } //判断过滤放行session缓存方法 if (req.getSession().getAttribute("user") != null) { System.out.println("过滤放行Session缓存"); chain.doFilter(request, response); return; } // 从Cookie获取上次保存的账号和密码 //取前端Cookie数据 Cookie[] cks = req.getCookies(); //判断Cookie是否为空 if (cks != null) { //循环遍历Cookie for (Cookie c : cks) { //判断Cookie的name为userCookie就执行 if (c.getName().equals("userCookie")) { //按@@分割Cookie的值 String[] us = c.getValue().split("@@"); //判断Cookie中账号密码是否正确 User u = Tools.authenticate(us[0], us[1]); //判断返回的集合是否为空 if (u != null) { //Cookie正确提示信息 System.out.println("Cookie正确设置 session"); //设置session到服务器 req.getSession().setAttribute("user", u); } } } } //判断过滤session是否为空 if (req.getSession().getAttribute("user") == null) { System.out.println("session为空重新加载到:/login页面"); rep.sendRedirect(req.getContextPath() + "/login"); return; } System.out.println("==============doFilter过滤器执行完毕!=============="); //过滤放行 chain.doFilter(request, response); } }
发表评论