1 public class LoginFilter implements Filter { 2 public void destroy() { 3 4 } 5 6 public void doFilter(ServletRequest request, ServletResponse response, 7 FilterChain chain) throws IOException, ServletException { 8 /* 9 * 1. 获取session中的user10 * 2. 判断是否为null11 * > 如果为null:保存错误信息,转发到msg.jsp12 * > 如果不为null:放行13 */14 HttpServletRequest req = (HttpServletRequest) request;15 Object user = req.getSession().getAttribute("sessionUser");16 if(user == null) {17 req.setAttribute("code", "error");//为了显示X图片18 req.setAttribute("msg", "您还没有登录,请先登录");19 req.getRequestDispatcher("你要跳转的登陆页面").forward(req, response);20 } else {21 chain.doFilter(request, response);//放行22 }23 }24 25 public void init(FilterConfig fConfig) throws ServletException {26 27 }28 }
web.xml配置如下LoginFilter LoginFilter 过滤器类路径 LoginFilter 你要过滤的页面 LoginFilter 你要过滤的servlet