在我的网站上我有一个文件夹 ../私人的/* 包含2个页面,我希望它们只能由登录用户访问。
如果我打开这两页数百次,我就可以正确地重定向到登录页面。 一旦我登录并打开页面,过滤器每页只调用一次,第二次打开页面时,过滤器不再被调用。
代码:
@WebFilter("/private/*")
public class FilterLoginPages implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
System.out.println("IN THE FILTER");
/* logic of session control */
/* some code, some code */
if(expiringDate != null && expiryDate.after(dateNow)){
System.out.println("user logged in correctly ..");
//open the page
request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response);
}else{
System.out.println("user not logged in ..");
//No logged-in user found, so redirect to login page.
response.sendRedirect(request.getContextPath() + "/login.html");
}
}
输出是"在过滤器"总是当我没有登录并且我尝试打开页面时,一旦我登录,我就会得到过滤器"在过滤器中#34;曾经,然后没有什么可以用于下一次开放。