Saturday, 27 September 2014

Cookies

As you know Http is stateless protocol. So, each time when any user request in web application, it will be new request. Hence we can not identify the user that user is already accessed the web resource or not.To avoid this web application has provided cookie mechanism to identify the user states.

Cookie is nothing but small filesystem in client browser, that can store some information. Cookie can be of two types-
  • Session cookies – Session cookies are stored in memory and are accessible as long as the user is using the web application. Session cookies are lost when the user exits the web application. Such cookies are identified by a session ID and are most commonly used to store details of a shopping cart.
  • Permanent cookies – Permanent cookies are used to store long-term information such as user preferences and user identification information. Permanent cookies are stored in persistent storage and are not lost when the user exits the application. Permanent cookies are lost when they expire.
Cookie is good option to store minimal value around 4k bytes of data to the client browser. Data always should be textual format. And cookie will not work if cookie option is disabled from the browser.



Creating the Cookie
 javax.servlet.http.Cookie class provide the functionality to create the cookie.

Cookie cookie = new Cookie("cookie-name" , "cookie-value")

You know now how to create the cookie but as earlier explain cookie stored inside client browser, so  response object help us to send cookie to the client browser by addCookie() method.

response.addCookie(cookie)

Reading Cookie
Whenever client sends new request, it submit cookie also. So cookie read by getCookies() method of request object.

Cookie[] cookies = request.getCookies();

for(Cookie cookie : cookies){
    if("cookie-name".equals(cookie.getName())){
        System.out.println(cookie.getValue());
    }
}

Removing Cookies
Removing the cookie is control by setMaxAge() method. This method takes int value from parameter expiry in second, if the passed parameter value is 0 then cookie will be removed immediately. And if passed parameter is -1 then cookie will be live until browser shutdown.

Cookie cookie = new Cookie("cookie-name" , "cookie-value");
cookie.setMaxAge(0);
response.addCookie(cookie);
 
Next chapter I will explain the next way of session tracking- next chapter 

No comments:

Post a Comment