In a typical visit to a web site, a user sends multiple requests for resources to a web server. If a web page contains many images (and most do!), then requesting the single web page involves one HTTP request for the HTML code and other template text (such as headlines and phrases), followed by separate requests for each image the web page contains. Future requests for the same page often return versions of these text and images that are cached on the client's computer for the sake of efficiency, depending on whether the fetched resources permit caching. At any rate, the server views each HTTP request for these web resources as separate and discrete from the other requests. Without the use of additional protocols, the server does not have a mechanism for managing client state , such as the progress of a web user through a questionnaire or storefront. Being able to logically relate one or more web requests as a single user session is where cookies come in.
A cookie is a small piece of information on a user's computer that a web server can use to identify that user the next time he visits the site. When a user initially visits the cookie-enabled site, the server responds with an extra response header that looks like:
Set-Cookie: mycookie=1051565332678; Domain=.myorg.com; Expires=Tue, 29-Apr-2003 07:42:12 GMT
Consequently, when the user visits the same site, his browser sends an extra request header that contains the cookie associated with that web location. Here is what the request headers look like when the client returns to the site that previously set the cookie; since the servlet container is Tomcat 4.1.12, the Cookie request header also includes a name /value pair for the session- related cookie ( JSESSIONID ):
GET /home/cookie HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/pdf, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0) Host: localhost:9000 Connection: Keep-Alive Cookie: JSESSIONID=F80F0F571FDE4873CFF3FF0B842D4938; mycookie=1051610231064
A cookie contains a name and a value; the cookie can also have several other optional attribute/value pairs, which are separated by semicolons:
The user can also disable cookies, so that his browser does not save any of the cookies in a web-server response. For example, in Netscape 7.1, the menu combination Edit Preferences Privacy & Security Cookies allows you to prevent the acceptance of cookies by choosing the "Disable cookies" radio button. In this case, the web developer uses "URL rewriting" for any clients that have disabled cookies (see Recipe 11.7 and Recipe 11.8).
The Java servlet API abstracts a cookie as an object of type javax.servlet.http.Cookie . The recipes in this chapter show how to create new cookies, as well as read or alter existing cookies, with both servlets and JSPs.