• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HttpSession - isValid()

 
Marcos Urata
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that Tomcat on his implementation class of HttpSession has a method called isValid() that verifies if the session is valid or not.

Is there any way to know if a session is still valid? I mean, if at any time the invalidate() method was called?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcos,
You can store an object in the session. For example, when the user logs in call session.setAttribute("valid", "");

When you get access to the session see if session.getAttribute("valid") is null. If so, the session was invalidated (and therefore all objects were unbound.) If it is not null, the session is still valid.
 
Joe Nguyen
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you get access to the session see if session.getAttribute("valid") is null. If so, the session was invalidated (and therefore all objects were unbound.) If it is not null, the session is still valid.

If you try to get attribute of an invalid session, you'll get a runtime exception named IllegalStateException.

Another way is to implements HttpSessionListener which will be notified when invalidate session occurs.
 
Ed Wallen
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Joe.........the best way is to use the HttpSessionListener. If you just wanted to find out if you have a session or not, you can do the following:

HttpSession session = request.getSession(false);
if (session != null) {
// You have a valid session established
}
else {
// There is no session established with the current request
}
 
Preetham Chandrasekhar
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HttpSession session = request.getSession(false);
//this line says if the session you get is not null then go ahead if there //does'nt exist a session dont create it.

//then u can check if the session is null or not by the following statements

if(session == null) {
//you can redirect the user to the error page or whereever u want him to go to
}
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe,
Good point. I had forgotten about that. My post applies to if invalidate() was called on a previous request.

Marcos,
You can still use the method I described; just wrap it in a try/catch block.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic