Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a session is invalid

How to check if a session is invalid or not? There is no method in the API.

Is it the same as isNew()? And what is the difference if not?

like image 919
iddober Avatar asked Mar 11 '09 15:03

iddober


People also ask

How do you check if a session is valid or not?

1) request. getSession(true);. The only problem is you do not know whether this is new or existed session. – Later you can check with “session. isNew()”, true if this is a new session else return an existed session.

How do you check session is exist or not in Java?

getSession() will always give you session object, so you can use request. getSession(false) code to get session and if session does not exist, it will return null.

How do you invalidate a session in a servlet?

To invalidate a session manually, call the following method: session. invalidate();


3 Answers

If you want to know whether it valid based on a request:

request.isRequestedSessionIdValid()    or  HttpSession sess = request.getSession(false); if (sess != null) {    // it's valid } 

If you have stored a reference to the session and need to validate I would

try {   long sd = session.getCreationTime(); } catch (IllegalStateException ise) {   // it's invalid } 
like image 131
John Wagenleitner Avatar answered Oct 08 '22 05:10

John Wagenleitner


isNew() is true only if this session wasn't yet accepted by client (i.e. it was just created, and JSESSIONID wasn't sent yet, or if it was sent, client didn't send it back, so server doesn't know about it and created another session)

like image 35
Peter Štibraný Avatar answered Oct 08 '22 04:10

Peter Štibraný


For all intents and purposes, yes. However, it will throw an IllegalStateException if called on a session invalidated in the same request-response cycle.

like image 31
Chry Cheng Avatar answered Oct 08 '22 04:10

Chry Cheng