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).
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();
String userid = createUserID(); // Create a unique ID Cookie c = new Cookie("userid", userid); resp.addCookie(c); // Add the cookie to the HTTP headers
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
Copyright © 2001 O'Reilly & Associates. All rights reserved.