views:

38

answers:

1

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

}
+1  A: 

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.

BalusC
thanx it work browser didn't go in infinte loop , and display login page , but when i change in url to private/secure.jsp it goes in infinte loop :( and didn't redirect to login page !! why?
Alaa
Probably you still have a login page in secured folder? Did you change `sendRedirect("login.jsp")` to `sendRedirect("/login.jsp")` ?
BalusC
the problem i found is that user get session even if he is not logged in ??? i don't know why, since i get session form http request in servlet after i assure from db connection , and then make session.setAttribute("Login", "ok"); and that what i check in filter , here: String logged = (String) session.getAttribute("login"); but i shock , user got session attribute login=ok but he didn't login!!!!!!!!!!!!!!!!!!!!!
Alaa
Likely your logout code is bogus. Restart your browser to create a new session.
BalusC