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[] ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.