package test.mylo.servlet; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** 逻辑:拦截所有的请求,放行index.jsp 和login的请求 判断当前的session里面是否有登录的信息 如果有的话就放行, 如果当前的session里面没有登录的信息,判断cookie里面是否有登录信息,如果有的话 放行 如果当前的session里面既没有登录信息,cookie里面也没有登录信息,就表示是第一次登录 如果请求的不是登录的方法(login)那么就让他进入到登录页面 */ @WebFilter("/*") public class AutoFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse) resp; String user =(String) request.getSession().getAttribute("loginUser"); if(user == null) { Cookie[] cookies = request.getCookies(); boolean flag = false; if(cookies != null) { for (Cookie c : cookies) { if(c.getName().equals("auto")) { String value = c.getValue(); request.setAttribute("loginUser", value); flag = true; break; } } } System.out.println( request.getRequestURI()); if(flag || request.getRequestURI().endsWith("index.jsp") || request.getRequestURI().endsWith("login")) { chain.doFilter(request, response); }else { response.sendRedirect(request.getContextPath() + "/index.jsp"); } }else { chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void destroy() { // TODO Auto-generated method stub } } |