在我们使用jsp的时候会用到过滤器,但是在某些请求我们不希望把他过滤掉,例如在登录页面我们的验证码也会发起请求,如果没有登录就没有办法访问到资源。我们需要把它排除在过滤的路径外面。
@WebFilter("/*")
public class LoginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession();
ArrayList allowPathList = new ArrayList();
//需要放行的页面
allowPathList.add("/login.jsp");
allowPathList.add("/VerifyCodeServlet");
allowPathList.add("/doLogin");
String currentUrl = httpRequest.getServletPath();
String erroMsg = "";
if(session.getAttribute("account")==null && !allowPathList.contains(currentUrl)) {
System.out.println(session.getAttribute("account"));
erroMsg = "尚未登录,请先登录";
request.setAttribute("erroMsg", erroMsg);
request.getRequestDispatcher("login.jsp").forward(request, response);
}
chain.doFilter(request, response);
}
}
这样我们就实现了我们对某些路径的放行