views:

370

answers:

3

Is there any other way to check expiry of session other than this

session.isNew()

+7  A: 

Yes:

  • you can call HttpServletRequest.getSession(false) and you'll get a null instead of a session if there isn't one active already.

  • you can define a lifecycle listener (using HttpSessionListener) in your web.xml. That way you can get notified the moment a session bites the dust.

Carl Smotricz
+1 for the second suggestion. BTW, its good to name it, so HttpSessionListener is the one.
Adeel Ansari
Implementing `HttpSessionListener` is the way to go. Just hook on `sessionDestroyed()`.
BalusC
you should just mark yourself best answer. How many points do you need to do that?
Yar
@yar: I think I'd have to be a moderator, and even (especially?) then it would be illegal. I have no problem with not being the winner on a question. Thanks, though!
Carl Smotricz
+4  A: 

Define a class, say SessionTimeoutIndicator, which implements the interface javax.servlet.http.HttpSessionBindingListener. Next create a SessionTimeoutIndicator object and add it to the user session. When the session is removed, the SessionTimeoutIndicator.valueUnbound() method will be called by the Servlet engine. You can then implement valueUnbound() to do the required operation.

hope its cleared now.

giri
Just using `HttpSessionListener#sessionDestroyed()` would make things more easy.
BalusC
A: 

With session.isNew you can not distinguish expired sessions from entirely new sessions. You can check if the session has expired and/or timed out with:

if (request.getRequestedSessionId() != null
        && !request.isRequestedSessionIdValid()) {
    // Session is expired
}

Use getRequestedSessionId to distinguish between new and existing (valid/expired) sessions, and use isRequestedSessionIdValid to distinguish betwheen valid and new/expired sessions.

You can put this code in a Filter.

Danilo Piazzalunga