O'Reilly logo

Java Enterprise in a Nutshell, Third Edition by William Crawford, Jim Farley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cookies

Very few software features have caused as much public confusion and outcry as the HTTP cookie. 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 this).[15]

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, which are subject to certain rules. The web application can use the cookie value to keep track of a particular user, handle session tracking, and so forth. Because cookies use a single Cookie header, the syntax for a cookie allows for multiple name/value pairs in the overall cookie value.

The Servlet API includes a class, javax.servlet.http.Cookie, that abstracts cookie syntax and makes cookies easy to work with. 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[] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required