Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existing session is invalidated or not?

Tags:

java

session

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();
}
like image 320
Manoj Avatar asked Jun 19 '13 05:06

Manoj


2 Answers

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.

like image 69
AllTooSir Avatar answered Oct 27 '22 02:10

AllTooSir


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;
}
like image 32
Arun P Johny Avatar answered Oct 27 '22 02:10

Arun P Johny