Home  Servlets  Servlet hosting  Servlets intro  Sessions  Cookies  HTTP headers  Status codes  Keep-alive

Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java
 Comment on this article  List of Java topics

Using Cookies with Java Servlets

Cookies are pieces of data that an HTTP client can be asked to associate with a web site or subsection of a web site1. Whenever the client requests a page, it sends along with the request any cookies that it was previously asked to associate with that web site and/or page. Cookies are used for cases where we need to "maintain state" across HTTP requests. In the real world, this typically means for the following purposes:

  • to create a temporary session where the site in some way "remembers in the short term" what the user was doing or had chosen between web page requests, e.g. remembering who the user is logged in as at the moment, or what they've ordered from an on-line "shopping cart";
  • to remember low-security information more permanently: for example, to remember a user's search results preferences or who they are logged in as on their social bookmarking site;
  • to compile user statistics, e.g. for advertising purposes or for improving the functionality of a site.

It's actually not so common to manipulate cookies directly. In the common case of handling sessions, the Java Servlet framework provides a Session API. If you're implementing sessions, it's generally a good idea to use the API designed for that purpose, for a few reasons:

  • the Session API should handle some security-related design issues;
  • there is general user paranoia around cookies that may put some people off using a site that appears to use them for a "non-standard" purpose (see this summary of studies on the user perception of cookies for more details);
  • both the specification and individual browsers often impose quite stringent limitations on cookies; it's more reliable to send a single, short string in a cookie (as is the case when using the Session API) than rely on being able to send longer data and/or a large number of cookies, as many browsers won't support this.

All that said, if you do want to manually set and read cookies from a Java Sevlet, then a Cookie API is provided.

1. Technically, cookies are restricted to a particular domain or subdomain and potentially a specific path of that domain/subdomain.

Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved.