Session Tracking : Cookies

Session Tracking :

Session simply means a particular interval of time. As we know that the Http is a stateless protocol, means that it can’t retain the information. It always treats each request as a new request. In a Http, client makes a connection to the server, sends the request, gets the response. and closes the connection. When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting request.
In session management, client first makes a request for any servlet or any page, the container receives the request and generates a unique session ID and gives it back to the client along with the response. This ID gets stored on the client machine. Thereafter when the client again sends a request to the server then it also sends the session id with the request. There the container sees the id and identifies the client and sends back the request.
There are four different techniques to achieve this:
1. Cookies 
2. Hidden Form Field 
3. URL Rewriting 
4. HttpSession 

Cookies :

javax.servlet.http.Cookie class provides the functionality of using cookies.

Cookies are the commonly used method for session tracking. Cookie is a key-value pair of info. sent by the server to the browser. Whenever the browser sends a request to that server it sends the cookie data along with it, so that server can identity the client using the cookie.

Advantage is, session tracking is easy to implement and maintain using the cookies.
Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client side and session tracking fails.

Cookie class provides a lot of useful methods for cookies :

String getName()
Returns the name of the cookie.
String getValue()
Returns the value of the cookie.
void setName()
Assigns a new name to a cookie after the cookie is created
void setValue()
Assigns a new value to a cookie after the cookie is created.
void setMaxAge(int expiry)
Sets the maximum age of the cookie in seconds.
For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces:
  • public void addCookie(Cookie cookie) : method of HttpServletResponse interface is used to add cookie in response object.
  • public Cookie[] getCookies() : method of HttpServletRequest interface is used to return all the cookies from the browser.
Example :




Leave a Reply

Your email address will not be published. Required fields are marked *