What is HttpSession?

We use HttpSession object to hold the conversational state across multiple client requests. In otherwords it persists for an entire session with a same client.
Can say for
same client- same client, same servlet, different request, different thread, same session
For another client- different client,same servlet, different request,diff thread, diff session.
For the container each request is from new new client because HTTP is stateless.
So how it happens? On the client’s first request the container generates a unique session ID and gives back to the client with the response. The client sends back the ID with each subsequent request. The container sees the ID, finds the matching session and associates the session with the request. You can never actually see the session id yourself.
Getting session id from the request,
HttpSession session=request.getSession();
It checks the session matching ID and if finds a matching, associates with the session. And if it does not get any matching ID then it creates a new session.
If we want that it will check only the pre-existing session, if it will not get it then will not create a new session, simple it will return null. It can be done by passing false parameter,
HttpSession session=request.getSession(false);
If there is no pre-existing session then the session object value will be null.
And the version getSession(true) is same as no argument.
HttpSession session=reguest.getSession(true); is exactly same as
HttpSession session=reguest.getSession();
We send data through session from one page to other. We have three method for this setAttribute(), getAttribute(), removeAttribute().
getId() :Returns the identifier assigned to this session
getSessionContext() :Returns the context in which this session is bound.
The HttpSession is only one for a given session ID per webapp, regardless of how many JVMs the webapp is distributed across.

No comments:

Post a Comment