Search code examples
servletshttpsession

Why do we need request.getSession(true)?


When I first started learning J2EE, I was told that, we need to call request.getSession(true) to create a new session. But when I started testing HttpSessionListener, I found that the servlet container will create a HttpSession as soon as it receives a Http request from the client - before I explicitly try to create any session. Is the servlet container implicitly calling request.getSession() or request.getSessioin(true) to create a new session from me?

The only scenario where I found the getSession(true) to be useful is when I want to explicitly invalidate the existing session and create a new one. Is this the only real world scenario or are there any other examples?


Solution

  • But when I started testing HttpSessionListener, I found that the servlet container will create a HttpSession as soon as it receives a Http request from the client - before I explicitly try to create any session

    I don't know how you tested it, but unfortunately it is not true. Try to create very simple servlet and put there:

    System.out.println("Session: " + request.getSession(false));
    

    you will see that session is null. Container doesn't create sessions, if it is not requested by your application.

    You probably got that impression testing jsp pages, or some framework, which by default create session. But this can also be disabled using <%@ page session="false" %>, if your page doesn't need session.

    And regarding need of request.getSession(true) - you could say it is not needed as request.getSession() does exactly the same, however request.getSession(false) is needed to check, if there is a valid session associated with request.