Monday 6 August 2012

Cookies in Servlet


Cookies are information which is stored in client browser. Cookies are used for information tracking about the client.

3 steps are there to store and process the  cookie :

1. First, server sends a set of cookies to client browser.

2. Then, client stored that cookies in local machine.

3. After client stores that cookie, if client send any more request to server, then that cookie information send with that request. From this information, server identify the client.


Create a cookie :

1. Cookie cookieobj = new cookie("cookieName", "cookieValue");

The name and value should not contain the following,

white space, (, ), [, ], =, /, ,, :, ;, ",@, and ?


2. By setting the age we can maintain the cookie.

cookieObj.setMaxAge(60*60*24);


3. Then need to add that created cookie into response. Then only it will send to client.

response.addCookie(cookieObj);


Accessing cookie in server :

1. We can access all the cookies which is comes from client request. By using getCookies();

request.getCookies()    ->      This will return array of cookies.

Aftet that, we can process the cookie and can access that.

/*
 * getting all cookies which is comes from client request
 */
Cookies[] allCookies = request.getCookies();

for (Cookie cookie in allCookies) {
    String name = cookie.getName();
    String value = cookie.getValue();
}



Deleting cookie:

1. By clearing the age of the cookie, we can clear the cookie.

First, get the appropriate cookie.

Cookies[] allCookies = request.getCookies();

for (Cookie cookie in allCookies) {
    if (cookie.getName.equals("cookieName")) {
        cookie.setMaxAge(0);    // clearing cookies
        response.addCookie(cookie);     // Adding cookie back to client response
    }
}