Cookies

A cookie is a small amount of information sent by a server to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.

The servlet sends cookies to the browser by first creating an instance of javax.servlet.http.Cookie and then using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

The browser returns cookies to the server by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes.

Example

// Fig. 19.9: CookieExample.java
// Using cookies.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieExample extends HttpServlet {
   private String names[] = { "C", "C++", "Java",
                              "Visual Basic 6" };
   private String isbn[] = {
      "0-13-226119-7", "0-13-528910-6",
      "0-13-012507-5", "0-13-528910-6" };

   public void doPost( HttpServletRequest request,
                       HttpServletResponse response )
      throws ServletException, IOException
   {
      PrintWriter output;
      String language = request.getParameter( "lang" );

      Cookie c = new Cookie( language, getISBN( language ) );
      c.setMaxAge( 120 );  // seconds until cookie removed
      response.addCookie( c );  // must precede getWriter
      
      response.setContentType( "text/html" );
      output = response.getWriter();         

      // send HTML page to client
      output.println( "<HTML><HEAD><TITLE>" );
      output.println( "Cookies" );
      output.println( "</TITLE></HEAD><BODY>" );
      output.println( "<P>Welcome to Cookies!<BR>" );
      output.println( "<P>" );
      output.println( language );
      output.println( " is a great language." );
      output.println( "</BODY></HTML>" );

      output.close();    // close stream
   }

   public void doGet( HttpServletRequest request,
                      HttpServletResponse response )
                      throws ServletException, IOException
   {
      PrintWriter output;
      Cookie cookies[];
      
      cookies = request.getCookies(); // get client's cookies

      response.setContentType( "text/html" ); 
      output = response.getWriter();

      output.println( "<HTML><HEAD><TITLE>" );
      output.println( "Cookies II" );
      output.println( "</TITLE></HEAD><BODY>" );

      if ( cookies != null ) {
         output.println( "<H1>Recommendations</H1>" );

         // get the name of each cookie
         for ( int i = 0; i < cookies.length; i++ ) 
            output.println(
               cookies[ i ].getName() + " How to Program. " +
               "ISBN#: " + cookies[ i ].getValue() + "<BR>" );
      }
      else {
         output.println( "<H1>No Recommendations</H1>" );
         output.println( "You did not select a language or" );
         output.println( "the cookies have expired." );
      }

      output.println( "</BODY></HTML>" );
      output.close();    // close stream
   }

   private String getISBN( String lang )
   {
      for ( int i = 0; i < names.length; ++i )
         if ( lang.equals( names[ i ] ) )
            return isbn[ i ];

      return "";  // no matching string found
   }
}

Running the Example

Select a programming language:

      C
C++
Java
Visual Basic 6


Press "Recommend books" for a list of books.


Selected API Documentation

javax.servlet.http.Cookie

Cookie

public Cookie(String name,
              String value)
Constructs a cookie with a specified name and value.

The name must conform to RFC 2109. That means it can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space or begin with a $ character. The cookie's name cannot be changed after creation.

The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie's value can be changed after creation with the setValue method.

By default, cookies are created according to the Netscape cookie specification. The version can be changed with the setVersion method.

Parameters:
name - a String specifying the name of the cookie
value - a String specifying the value of the cookie


setValue

public void setValue(String newValue)
Assigns a new value to a cookie after the cookie is created. If you use a binary value, you may want to use BASE64 encoding.

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

Parameters:
newValue - a String specifying the new value

javax.servlet.http.HttpServletRequest

getCookies

public Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.

Returns:
an array of all the Cookies included with this request, or null if the request has no cookies

javax.servlet.http.HttpServletResponse

addCookie

public void addCookie(Cookie cookie)
Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.

Parameters:
cookie - the Cookie to return to the client


Maintained by John Loomis, last updated 14 Feb 2001