1 /** 2 * 登录的过滤 3 * @author 王东海 4 * @2017年4月17日 5 */ 6 7 @WebFilter(filterName="LoginFilter",urlPatterns={"*.do","*.jsp"}) 8 public class LoginFilter implements Filter { 9 10 @Override 11 public void destroy() { 12 13 } 14 15 @Override 16 public void doFilter(ServletRequest arg0, ServletResponse arg1, 17 FilterChain chain) throws IOException, ServletException { 18 /** 19 * 首先确定哪些资源拦截,哪些资源不拦截 20 * 1.资源拦截定义 21 * servlet下不拦截的:userLoginController.do 22 * userLoginOutController.do 23 * userRegistrerController.do 24 * jsp下不拦截的:login.jsp 25 * register.jsp 26 * 2.其他的我们需要拦截,accountManagerController.do, 27 * 需要判断session里user是否存在, 28 * 如何存在,放行;不存在,跳转到登录页面,进行登录 29 */ 30 31 //1.进行下转换 32 HttpServletRequest request = (HttpServletRequest) arg0; 33 HttpServletResponse response = (HttpServletResponse) arg1; 34 35 String uri = request.getRequestURI(); 36 37 //判断哪些包含放行的 38 if (uri.indexOf("userLoginController.do") >-1 39 || uri.indexOf("userLoginOutController.do") > -1 40 || uri.indexOf("userRegistrerController.do") > -1 41 || uri.indexOf("login.jsp") > -1 42 || uri.indexOf("register.jsp") > -1 43 ) { 44 45 chain.doFilter(request, response); 46 return; 47 } 48 49 50 User user = (User) request.getSession().getAttribute("user"); 51 if (user == null) { 52 //如果用户名为空,我就重定向 53 response.sendRedirect("login.jsp"); 54 return; 55 } 56 57 chain.doFilter(request, response); 58 } 59 60 @Override 61 public void init(FilterConfig arg0) throws ServletException { 62 63 } 64 65 }