Filter passes before login Servlet

Asked

Viewed 165 times

1

Good evening guys, I have a question, I don’t even know if I need to post the code to solve.

The filter is being called before the login Servlet, that is, with that the user is never logged in.

How do I get Servlet to be called before? Remembering that I don’t use web.xml....

If there is no other way, someone can help me to do web.xml correctly?

From now on. Thank you.

1 answer

1


From your description, I’m assuming you have a Servlet to validate whether the user/password is valid, and a filter that only checks whether the user is logged in or not. This separation is correct, and you don’t need to call Servlet before, just allow access to the login page:

@WebFilter("/*")
public class LoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURI = request.getContextPath() + "/login";

        boolean loggedIn = nonNull(session) && nonNull(session.getAttribute("user"));
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }
}

This way access to the login page is always valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.