Manoj
Manoj

Reputation: 329

How to check existing session is invalidated or not?

How can i check existing session is invalidated or not? In the following loginBean code i checked every login the user already loggedin or not. If already loggedin by other system, deactivate that session and creating new. if that session was invalidated by time out, next time userSessionMap contain usedname and error to invalidate. so how to check it is invalidated?

Map appMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
Map<String, HttpSession> userSessionMap = (Map<String, HttpSession>) appMap.get("USERS");

if (userSessionMap.containsKey(getUsername())) {
log.info(getUsername() + " already loggedin. Closing existing sesssion");
HttpSession sess = userSessionMap.get(getUsername());
sess.invalidate();
}

Upvotes: 8

Views: 29601

Answers (2)

AllTooSir
AllTooSir

Reputation: 49372

Try passing false as the parameter to the getSession(boolean) . This will give back a session if it exists or else it will return null.

HttpSession session = request.getSession(false);
if (session == null || !request.isRequestedSessionIdValid()) {
    //comes here when session is invalid.        
}

Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null.

Upvotes: 13

Arun P Johny
Arun P Johny

Reputation: 388316

HttpSession session = request.getSession(false); will give IllegalStateException if the session is already invalidated

boolean invalidated = false;
try {
    request.getSession(false);
} catch(IllegalStateException ex) {
    invalidated = true;
}

Upvotes: 12

Related Questions