A cookie, developed by the Netscape Corporation is a small piece of information that the HTTP server sends to the browser when the browser starts a new connection and later read back from the client. The cookies are used to handle the stateless nature of HTTP protocol by using them as a user session identifier. A cookie can be large as 4 Kb or 4000 characters in length and are not shared by browsers.
Cookie has six attributes. Only name and value attributes are mandatory where as others are optional.
Creating cookie
In Java the Servlet API has a Cookie class to implement cookies and their read /write functionalities. In order to set a cookie in the client, first we need to create a cookie then add it to the response. The cookie constructor accept two arguments as cookie name and corresponding value.
Cookie cok = new Cookie(“cookie_name”, cookie_value);
//setting cookie attributes
cok.setMaxAge(30 * 60);
cok.setPath(“/path/”);
cok.setDomain(“.domain.com”);
cok.setSecure(true)
//adding cookie to response
response.addCookie(ck);
Reading cookies
In order to read the cookies ,we need to traverse through the cookie list obtained from the request object (since there may be different cookies in same name ,we cannot address cookies by their name)
//read cookies from request object it will return null if there is no cookie.
Cookie[] cookies = req.getCookies();
Cookie[] cookies = req.getCookies();
if (cookies != null)
for (Cookie cok : cookies) {
if (“pref_name”.equals(cok.getName())) {
String pref_value = cok.getValue();
}
Deleting cookies
If we want to delete a cookie ,set the cookie as the above example but set the maximum age as zero. If you want to delete the cookie at each browser session end ,create cookie with its default behavior then set the maximum age a negative value.
Advantages
Disadvantage
Cookies will provide a better and efficient alternative for storing user-specific data in client location. Cookies allows a better caching strategy to make the sites more fast and scalable.