start page | rating of books | rating of authors | reviews | copyrights

Book Home Java Enterprise in a Nutshell Search this book

5.7. Cookies

Cookies spent a year or two as a little-known feature of Netscape Navigator before becoming the focus of a raging debate on electronic privacy. Ethical and moral considerations aside, cookies allow a web server to store small amounts of data on client systems. Cookies are generally used to store basic user identification or configuration information. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking (although, as we'll see shortly, the Servlet API provides higher-level support for session tracking).

To create a cookie, the server (or, more precisely, a web application running on the server) includes a Cookie header with a specific value in an HTTP response. The browser then transmits a similar header with that value back to the server with subsequent requests, subject to certain rules. The web application can then use the cookie value to keep track of a particular user, handle session tracking, or whatever. Because cookies use a single Cookie header, the syntax for a cookie allows for multiple name/value pairs in the overall cookie value.

More information about the cookies is available from the original Netscape specification document at http://home.netscape.com/newsref/std/cookie_spec.html. The Internet Engineering Task Force is currently working on a standard cookie specification, defined in RFC-2109, available at http://www.internic.net/rfc/rfc2109.txt.

The Servlet API includes a class, javax.servlet.http.Cookie, that abstracts cookie syntax and makes it easy to work with cookies. In addition, HttpServletResponse provides an addCookie()) method, and HttpServletRequest provides a getCookies() method, to aid in writing cookies to and reading cookies from the HTTP headers, respectively. To find a particular cookie, a servlet needs to read the entire collection of values and look through it:

Cookie[] cookies;
cookies = req.getCookies();
String userid = null;

for (int i = 0; i < cookies.length; i++) 
  if (cookies[i].getName().equals("userid"))
    userid = cookies[i].getValue();

A cookie can be read at any time, but can be created only before any content is sent to the client. This is because cookies are sent using HTTP headers and these headers can be sent to the client before the regular content. Once any data has been written to the client, the server can flush the output and send the headers at any time, so you cannot create any new cookies safely. You must create new cookies before sending any output. Here's an example of creating a cookie:

String userid = createUserID();          // Create a unique ID
Cookie c = new Cookie("userid", userid);
resp.addCookie(c);                       // Add the cookie to the HTTP headers

Note that a web browser is only required to accept 20 cookies per site and 300 total per user, and the browser can limit each cookie's size to 4096 bytes.

Cookies can be customized to return information only in specific circumstances. In particular, a cookie can specify a particular domain, a particular path, an age after which the cookie should be destroyed, and whether or not the cookie requires a secure (HTTPS) connection. A cookie is normally returned only to the host that specified it. For example, if a cookie is set by server1.company.com, it isn't returned to server2.company.com. We can get around this limitation by setting the domain to .company.com with the setDomain() method of Cookie. By the same token, a cookie is generally returned for pages only in the same directory as the servlet that created the cookie or under that directory. We can get around this limitation using setPath(). Here's a cookie that is returned to all pages on all top-level servers at company.com:

String userid = createUserID();   // Create a unique ID
Cookie c = new Cookie("userid", userid);
c.setDomain(".company.com");      // *.company.com, but not *.web.company.com
c.setPath("/");                   // All pages
resp.addCookie(c);                // Add the cookie to the HTTP headers


Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.