Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Checking to see if a session has expired

 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to check to see if the session has expired and if it has redirect the user to the login page.
Here is my code
HttpSession session = request.getSession( false );
if ( session == null ){
//redirect user to login page
}
Is this ok? One other option was to check the time the users session was last active. Using milliseconds minus the current time from the time the user last used the session and check to see if that time is greater than the time specified in the web.xml file.<session-timeout>
What is the best way do you think?
Or is there a better way?
Regads david
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems to me it would be simpler to set the maxInactiveInterval for this particular session and rely on the servlet engine to deactivate the session.
Then use your session == null check.
If the servlet engine is working right, I think you should never detect a time last used outside the value specified in web.xml unless your application changes it directly.
Bill
 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use the .isNew() method to check to see if the user has a valid session object. For example. Session session = req.getSession(); Then later on in the code or before a method call just use the session.isNew() which returns a boolean true if the user does not currently know about the session or if the session has expired.
 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought the isNew() function checked if the user had ever had a session not if it was current or not.
So would the isNew() return true if it was the first time the use had visited the site
and
would the isNew() return false if the user had visited the site before (ignoring whether the session was valid or had expired).
Thanks
david
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The isNew return is true if the session was just created - it doesn't know a thing about previous visits. When a session tests new, the user does not yet have a cookie for it. This is all detailed in the servlet API.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic