| Author |
Checking to see if a session has expired
|
david allen
Ranch Hand
Joined: Sep 27, 2002
Posts: 185
|
|
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
Joined: Mar 22, 2000
Posts: 12266
|
|
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
|
Java Resources at www.wbrogden.com
|
 |
Sloan Bowman
Ranch Hand
Joined: Jan 21, 2003
Posts: 107
|
|
|
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
Joined: Sep 27, 2002
Posts: 185
|
|
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
Joined: Mar 22, 2000
Posts: 12266
|
|
|
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.
|
 |
 |
|
|
subject: Checking to see if a session has expired
|
|
|