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中的user 10 * 2. 判断是否为null 11 * > 如果为null:保存错误信息,转发到msg.jsp 12 * > 如果不为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配置如下 <filter> <display-name>LoginFilter</display-name> <filter-name>LoginFilter</filter-name> <filter-class>过滤器类路径</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>你要过滤的页面</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LoginFilter</filter-name> <servlet-name>你要过滤的servlet</servlet-name> </filter-mapping> </filter-mapping>