request.getSession (false) always returning a session

Recently I found that request.getSession (false) was *always* returning a session instance even when it is not created earlier by my application. After spending 2-3 hours on it, I figured out the cause. Read on …….

I am working on adding a rather unique jobs functionality for chahiye.info which required an authentication mechanism. For this purpose, I wanted to add a check at various pages to ensure that if a session did not exist a request to these pages would be re-directed to loign page. This was done using the following code

HttpSession session = request.getSession (false);
if (session == null)
{
// forward request to login page
// return;
}

However to my surprise this api was always giving me a session instance even when I had not explicitly created one (after the login request). I searched my entire code base & confirmed that I was not creating a session anywhere. Looked up the JavaDoc for this method in class javax.servlet.HttpServletRequest, which clearly stated that if the supplied boolean is false and if the request has no valid HttpSession, this method would return null.

After spending some more time, I realized the problem. Basically if the application is using a JSP, the container (in my case Tomcat 5.5) by default ends up creating a session. In my case, the user’s landing page itself was a JSP as a result the session gets created at that time itself. To avoid this, simply add the following directive at your JSP, which tells the JSP compiler not to use session variable in the compiled class.

< % @page session="false" % >

Note – You will have to get rid of extra spaces between “<“, “%” & “@” symbols.

Have you also had a similar situation and figured out another cause for this? If yes, please share your experience here.

Advertisements

6 thoughts on “request.getSession (false) always returning a session

  1. Yeah, that is easy to miss :). As “session” is one of the nine implicit objects, provided by the container on jsp page, we need to specifically mention that we don’t need it on the page.

  2. I had also faced the same problem,
    And found the same.
    Its a very critical thing when we are thinking of session management.

  3. Abhishek,

    It should now be visible. Just realized that the snippet was not visible on IE 6 (I mostly use firefox for browsing).

    Have now added spaces between < and % symbols to get around the problem.

    –guneet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s