I am facing very strange problem while developing JavaEE WEB Application.
Even after invalidating the HttpSession
using session.invalidate();
, I am not getting session null
. There is a case where I have one statement in execution like below after invalidating session.
if (null != session && null != session.getAttribute("loginToken")){
//do something
}
I am not getting session null here so second condition will try to execute. And hence session is not null, so I am getting IllegalStateException
- session is already invalidated
. But why session is not null after invalidating it?? :(
The invalidate method does the following (from API):
Invalidates this session then unbinds any objects bound to it.
It says nothing about the
HttpSession
-object itself, but invalidates the session's variables. If you call a method of a class, it is impossible for the object to benull
after that method call. If your session should be null afterwards, the method must include a line that looks something like:this = null;
which would not be possible. Throwing an exception for an invalidated session is the prefered way to do it.Calling
session.invalidate()
removes the session from the registry. CallinggetSession(false)
afterwards will return null (note thatgetSession()
orgetSession(true)
will create a new session in this case). Callinginvalidate()
will also remove all session attributes bound to the session. However if your code still has references to the session or any of its attributes then these will still be accessible:Example output:
So far for the explanation. To solve your problem you should do:
Try passing false as the parameter to the getSession(boolean) . This will give back a session if it exists or else it will return null.