I have got two HTML files
My requirement is that the User shouldn\'t able to access test.html unless he logs i
This AuthenticationFilter also runs when login.html is being requested. However, the code is redirecting to login.html once again instead of continuing the filter chain. This explains the infinite redirect loop.
You need to let the filter just continue the request if the currently requested page is already the login page itself.
E.g.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
String loginURL = req.getContextPath() + "/login.html";
boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean loginRequest = loginURL.equals(req.getRequestURI());
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
res.sendRedirect(loginURL);
}
}