sarah
sarah

Reputation: 2397

How to check if session exists or not?

I am creating the session using

HttpSession session = request.getSession();

Before creating session I want to check if it exists or not. How would I do this?

Upvotes: 24

Views: 100586

Answers (5)

rakke
rakke

Reputation: 7119

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: HttpServletRequest.html

cheers, Jørgen

Upvotes: 5

I would like to add that if you create a new session for every new user connecting to your website then your performance will take a hard hit. Use request.getSession(false) to check if a user has a session. With this method you don't create a new session if you're going to render a view based on if a user is authenticated or not.

Upvotes: 4

Ahmed Hassan Hegazy
Ahmed Hassan Hegazy

Reputation: 71

if(null == session.getAttribute("name")){  
  // User is not logged in.  
}else{  
  // User IS logged in.  
}  

Upvotes: 6

BalusC
BalusC

Reputation: 1108722

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

Upvotes: 41

aioobe
aioobe

Reputation: 420991

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.

Upvotes: 23

Related Questions