palAlaa
palAlaa

Reputation: 9858

Infinite loop when using filter for jsp files

When I make filter for all jsp pages, the browser goes into an infinite loop, but when I make filter for only one page, it runs correctly!!

Here is doFilter method, if some one find the error plx tell me...

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    if (debug)  log("AuthenticationFilter:doFilter()");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpServletResponse httpres = (HttpServletResponse) response;
    HttpServletRequest httpreq = (HttpServletRequest) request;

    if (httpreq.getRequestURI().indexOf("login.jsp") == -1 || httpreq.getRequestURI().indexOf("LoginServlet") == -1) {
   // if(!httpreq.getRequestURL().equals("/OSQS/Login.jsp")){
        HttpSession session = httpreq.getSession();
        String logged = (String) session.getAttribute("login");

        if (logged == null) {
            httpres.sendRedirect("login.jsp");
            return;
        }
    }
    chain.doFilter(request, response);

}

Upvotes: 0

Views: 3545

Answers (1)

BalusC
BalusC

Reputation: 1108722

The cause of this problem is that the filter's url-pattern is apparently too generic, e.g. /* or maybe *.jsp. It will be executed on every JSP request.

In the filter you're sending a redirect to login.jsp when the logged in user is absent. A redirect will instruct the client to fire a new HTTP request. A new HTTP request will invoke the filter again when the request URL matches its url-pattern. Because the logged in user is still absent, it goes into an infinite redirect loop.

Apart from determining the request URL (as you did), you can also just place the secured pages on a more specific url-pattern, e.g. /secured/*, /private/* or so and then place the secured pages there, but the login page not. If you redirect to the login page, then the filter won't be invoked more.

Upvotes: 3

Related Questions