Servlet logo
Servlet Tutorial

Overview  
HTTP/CGI  
Servlets  
JSP  
Resources  

Zameer's Education


 

Introduction | Servlets & HTTP | Life-Cycle | Sessions | Summary | Examples

Sessions: HTTP Session Tracking | Cookies | Servlet Sessions | Sessions At Work

Cookies

A cookie is a small piece of information passed by the web server for storage at the client. In terms of anonymous session tracking, we want the cookie to at least store a unique session id for the client browser. The guys at Netscape brought us cookies and since then they have been adopted as a defacto standard by all major web browsers. Cookies are an ideal way for a web server to store small pieces of information such as session ids, at the browser, that can be read back at a later time by the server when the client accesses certain pages at its site. Because of the one-to-one mapping between a browser and its cookies, cookies provide a good, standard solution for anonymous session tracking.

Cookies are encoded as part of the header information for an HTTP request or response. To store a cookie at the browser, the servlet must add the cookie HTTP header information to its response. To retreive information from a cookie, a servlet needs to extract the cookie HTTP header details from its request. The Servlet API has made this easy by providing a Cookie class that takes care of the getting/setting of HTTP header information into requests/responses. Instead there is no talk of HTTP header information, you simply addCookie() and getCookies(). Simple!

Examples....

So are cookies the answer to the web state problem? Well, yes and no. If as a servlet developer you can guarantee that all browsers will accept your cookies then you've solve the anonymous session tracking problem. But its not as simple as that. It's not that browsers don't support cookies, because the majority do, its just that they have the ability to turn off cookies. In doing so, the browser will not store any cookies passed by the server and bang goes you session tracking. Why do people turn off cookies in their browsers? Issues of security are often cited as a reason and this is enough for certain corporates and individuals to turn of cookies support in their browsers.

In the absence of cookies you can implement either the remote user, hidden form fields or URL rewriting techniques described in the previous sections. But as a servlet developer, you are blessed with good fortune. The servlet API provides its own Session Tracking API for takes away the mundane and tedious efforts of maintaining sessions in your web applications.