How container decides to destroy the session?

HTTP protocol has no mechanism for the server to know that the client is gone. Here is a question that how container decides to end the session. We can handle it in different ways,
Sometimes we would like to recognize when a session has been inactive for too long(time is user defined) and destroy the session.
We have some methods in HttpSession to handle this,
getCreationTime() – Returns the time when session was first created. You might want to restrict certain session to a fixed length of time.

getLastAccessTime() – Returns the last time when the container got request with this session id(in milliseconds). You might use to decide that if the client is gone for too long and and invalidate the session.

setMaxInactiveInterval() – Specifies the maximum time in seconds that you want to allow between client requests for the session. To cause a session to be destroyed after a certain amount of time has passed without the client making any any request for this session.

setMaxInactiveInterval() – Returns the maximum time in seconds that is allowed between client requests for this session.. To find out how long this session can be inactive.

Invalidate() – Ends the session This includes unbinding all session attributes currently stored in the session. To kill the session when client is inactive for a long time or if you know that the session is over.

Three ways a session can die:
1)It times out
2)You call the invalidate() methodon the session object
3)The application goes down(crashes or undeployed)

Setting session time out for a specific session:
If you want to change the value of session time out value for a specific session(without affecting the time out length for any other session in web webapp),
It affects only the session on which it is called. The argument to the method is in seconds. Here it will invalidate the session after 20 minutes.

We can also mentain session time out in DD also.
The time(15) is in minutes. It says if the client does not make any request for 15 minutes then kill the session. It is same as calling setMaxInactiveTime(15*60) on every session that is created.
You can not call the isNew() method on a session that is already invalidated. If you do so it throws IlligalStateException at runtime.

No comments:

Post a Comment