Filter passes before the login servlet

1

Good evening, I have a question, I do not even know if I need to post the code to solve it.

The filter is being called before the login servlet, ie the user is never logged in.

How do I get the servlet called before? Remembering that I do not use web.xml ....

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

Right now. Thank you.

    
asked by anonymous 30.05.2017 / 23:05

1 answer

1

By its description, I'm assuming you have a servlet to validate if 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 do not need to call the 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.

    
31.05.2017 / 11:55