Cookies and Session Management
Cookies are small pieces of information that are sent in response from the web server to the client. Cookiesare the simplest technique used for storing client state.
Cookies are stored on client’s computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan.
Using Cookies for storing client state has one shortcoming though, if the client has turned of COokie saving settings in his browser then, client state can never be saved because the browser will not allow the application to store cookies.
Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the
addCookie() method. This method sends cookie information over the HTTP response stream.
getCookies() method is used to access the cookies that are added to response object.
Session Tracking in Servlets
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
- Hidden Form Field
- URL Rewriting
Using URL Rewriting for Session Management
If the client has disabled cookies in the browser then session management using cookie wont work. In that case URL Rewriting can be used as a backup. URL rewriting will always work.
In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair seperated by an
When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of information at the end of URL. The Web Container will fetch the extra part of the requested URL and use it for session management.
getParameter() method is used to get the parameter value at the server side.
Hidden form field can also be used to store session information for a particular client. In case of hidden form field a hidden field is used to store client state. In this case user information is stored in hidden field value and retrieved from another servlet.
- Does not have to depend on browser whether the cookie is disabled or not.
- Inserting a simple HTML Input field of type hidden is required. Hence, its easier to implement.
- Extra form submission is required on every page. This is a big overhead.