Cookies serve as a facility for servers to send information to a client.†† This information is then housed on the client, from which the server can later retrieve the information.†In this article, we will study the concept of saving client state with cookies using Java Servlets.†Iíll walk you through an end to end example where you will store and retrieve data using cookies.
Before we delve deeper into the handling of cookies, letís cover some basic background information about the subject. Java Servlets (which reside on the server) send cookies to clients by adding fields to their HTTP response headers. Similarly, clients return cookies to servers by adding fields to HTTP request headers. When a client application (e.g., a Web browser) receives a cookie from a web server, the client application stores the cookie locally. Upon subsequent request to the web server, the cookie will be returned. You can learn more about cookies by reading the Netscape specification (see resources section).
Figure 1: Cookie Transmission Over the Network
The server can send multiple cookies to the client. Each cookie is sent as a separate response header. The same is true for the client talking back to the server, except that there, we are dealing with multiple request headers. It is important to note that you can have cookies with the same name. For example, I might have an application where I send the server two cookies with headers both named Citizenship. Letís say I have dual citizenship; in such a case, I might send two cookies with two different country names as values.
What Can I Store in A Cookie?
The javax.servlet.http.Cookie object allows you to set a name and an associated value. Also, it allows you to set a comment as an optional attribute. You can see the setters associate to the Cookie object in the figure below. Refer to the javadoc of the javax.servlet.http.Cookie class for a complete breakdown of the classís API.
Figure 2: The Setters Associated to the CookieObject
When you call the constructor of a Cookie, you set its name and value. The name of the cookie must be an HTTP/1.1 ďtoken.Ē A token is a string that does not contain characters listed in RFC 2068. Your safe bet is to use an alphanumeric string as your token. Values of your cookie can be any string. However, if you want to be prudent and stick to specification, the original Netscape cookie specification prohibits the use of the following characters:
[ ] ( ) = , " / ? @ : ;
Note that you can override the value you set for a cookie via the constructor later by calling the Cookie objectís setValue method.
Studying Some Working Code
The code mentioned throughout this article for demonstrative purposes can be downloaded here. The code is bundled as an enterprise application archive (EAR) so you can deploy it to your application server of choice.