1 @WebFilter(dispatcherTypes = {DispatcherType.REQUEST } 2 , urlPatterns = { "/*" }) 3 public class Filter1 implements Filter { 4 5 public Filter1() { 6 } 7 8 public void destroy() { 9 } 10 11 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 12 13 HttpSession session=((HttpServletRequest)request).getSession(); 14 boolean isAllowed=true; 15 if(session.getAttribute("user")==null){ 16 if(!((HttpServletRequest)request).getServletPath().equals("/login.jsp")) 17 isAllowed=false; 18 } 19 if(isAllowed) 20 chain.doFilter(request, response); 21 else 22 ((HttpServletResponse)response).sendRedirect("login.jsp"); 23 24 } 25 26 public void init(FilterConfig fConfig) throws ServletException { 27 } 28 29 }
当用户访问所有资源时,如果用户未登录,就跳转回登录页面.