views:

215

answers:

4

I am creating the session using HttpSession session=request.getSession(); before creating session i want to check if session is existing or not,how would i do this?

+5  A: 

There is a function request.getSession(boolean create)

Parameters:
    create - true to create a new session for this request if necessary; false to return null if there's no current session

Thus, you can simply pass false to tell the getSession to return null if the session does not exist.

aioobe
...best explaination imho... refers to docs and keeps focused.
Daniel Bleisteiner
+2  A: 

Hi,

HttpSession session = request.getSession(true);
if (session.isNew()) {
  ...do something
} else {
  ...do something else
}

the .getSession(true) tells java to create a new session if none exists.

you might of course also do:

if(request.getSession(false) != null){
    HttpSession session = request.getSession();
}

have a look at: http://java.sun.com/javaee/6/docs/api/javax/servlet/http/HttpServletRequest.html

cheers, Jørgen

rakke
You would have to pass `false` to the second `.getSession()`.
aioobe
sorry... Typo. corrected. Thanks.
rakke
+4  A: 

If you want to check this before creating, then do so:

HttpSession session = request.getSession(false);
if (session == null) {
    // Not created yet. Now do so yourself.
    session = request.getSession();
} else {
    // Already created.
}

If you don't care about checking this after creating, then you can also do so:

HttpSession session = request.getSession();
if (session.isNew()) {
    // Freshly created.
} else {
    // Already created.
}

That saves a line and a boolean. The request.getSession() does the same as request.getSession(true).

BalusC
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.

giri