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