John Park John Park - 1 year ago 97
Java Question

Endless loop when logging in with Servlet Filter and j_security_check

I have implemented a servletFilter and declared it in my web.xml but the issue is I cant login now. The user submits their username and password and the code redirects to a j_security_check page and then reloads logon.html again endlessly. In the code doFilter(req,res) is hit both times, the sendRedirect code used to send back to logon.html is never used.

Is there another element im missing? Ive read that servlet filters and j_security_check dont always play nice but I thought I could find a work around.


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);

String loginURI = request.getContextPath() + "/logon.html";
String securityURI = request.getContextPath() + "/j_security_check";

boolean loggedIn = session != null && session.getAttribute("user") != null;
boolean securityRequest = request.getRequestURI().equals(securityURI);
boolean loginRequest = request.getRequestURI().equals(loginURI);

if (loggedIn || loginRequest || securityRequest) {
chain.doFilter(req, res);
} else {

so the code checks if the request is coming from the logon page or the j_security_check page and processes doFilter if they are. This is working but im not sure why its not processing through to the application if its passing both times?





Answer Source

Try reversing your condition in the filter like this.

if (!loggedIn || !loginRequest || !securityRequest) {
} else {
    chain.doFilter(req, res);