3

I am using the following code to delivery the user to a Welcome page if they are already logged in, or back to the login page if they are not.

        HttpSession session = request.getSession(false);

    if(session == null){
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }else{
        //User already logged in. Send to home.
        response.sendRedirect("Welcome");
    }

First time around, it works fine, but if I reload the page even once it sends the user to the welcome page and inevitably sends me back a 500 error because there are elements on that page that cannot be loaded because the user log in code has not been executed.

Does a session get started automatically even if request.getSession(true) is not declared when a page is reloaded? Is there a way to prevent this?

ryandlf
  • 27,155
  • 37
  • 106
  • 162

2 Answers2

2

Probably the session is being created upon forwarding to login.jsp. That's necessary because the user has to be assigned to an unauthenticated request and then authenticate it. If you want to redirect based on whether the user is logged in or not, use SessionContext's getCallerPrincipal.

For more info, check this (somewhat old, but still relevant) article

PaoloVictor
  • 1,296
  • 8
  • 18
0

The method request.getSession(false) returns null if there is no current session. I suggest to compare a key too.

Please take a look at this threads.

  1. Do JSPs always create a session?
  2. How do servlets work? Instantiation, session variables and multithreading
Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 1
    I agree with this. Don't rely on nullness of the season to see if the user is logged in or not. When he logs in, set an attribute (e.g. `session.setAttribute("userId", user.getId())` and use that to see if the user is logged in or not. Otherwise if you want to use the built-in security mechanisms provided by JEE, @PaoloVictor's solution makes more sense. – Behrang Oct 04 '11 at 02:57