Return to Servlet index

Cookies

Cookies provide a way for a server (or a servlet running on a server) to send some information to a client to store, and for the server (servlet) to later retrieve from that client.

Servlets send cookies to clients by adding fields to HTTP response headers. Clients automatically return all cookies that match the domain name of the requested URL by adding fields to HTTP request headers. The servlet writer will employ methods for getting and setting cookies that are part of classes HttpServletRequest and HttpServletResponse - the server handles the coding and decoding of the HTML headers.

Cookies are often used for session tracking, but can also be used for maintaining other client state information.

Cookies are written (in the HTML headers) as 'name=value' strings; to create a new Cookie, the code would be, for example:

Cookie myCookie = new Cookie("BookToBuy", "304qty1")

The strings must contain only alphanumeric characters and no spaces. You can change the value of the cookie later with its setValue method.

Multiple cookies can have the same name. For example, a servlet could send two cookies with headers named BookToBuy; one could have the value shown previously, 304qty1, while the other could have the value 301qty3. These cookies would indicate that the user wants to buy one copy of the book with stock number 304, and three copies of the book with stock number 301 (the meaning of the values is totally arbitrary and programmer defined). Only if both name and value are identical to an existing cookie, will it be overwritten when stored on the client.

In addition to a name and a value, you can also provide optional attributes such as comments. Current web browsers do not always treat the optional attributes correctly, so you should not rely on them.

A server can provide one or more cookies to a client. Client software, such as a web browser, is expected to support at least twenty cookies per 'host' (domain - e.g. kinabaloo.com).

Cookies that a client stores for a server are returned by the client to that server, and only that server, whenever a page is requested from that server (i.e. from that domain or 'host'). A server can contain multiple servlets. Hence, because cookies are returned to a server, all the servlets running within the server can share the cookies. This is one way to allow servlets to share information (they can also share other java classes).

 

How to create and send a cookie

There are 3 steps :

  1. Instantiate a Cookie object
     
  2. Set any attributes, such as it's maximum age (how long it should persist on the client)
     
  3. 'Send' the cookie - simply add it to the HttpServletResponse object (which handles the actual header writing). If your servlet returns a response to the user with a Writer, add the cookie before accessing the Writer.
     

Here is an example :

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

...

// If the user wants to add a book, you can remember it by adding a cookie

String bookId = request.getParameter("Add");

Cookie buyBook = new Cookie("Buy", bookId);

buyBook.setMaxAge(60*60); // 1 hour

buyBook.setComment("User has indicated a desire to buy this book.");

response.addCookie(buyBook);

// set content-type header before accessing the Writer

response.setContentType("text/html");

// now get the writer and write the response

PrintWriter out = response.getWriter();

out.println("<html><body><p>..." + ...

...

}

 

Note the order of : 1) add cookie, 2) set content type, 3) get writer.

One useful attribute is the maximum age of the cookie. The method to set this attribute is:

setMaxAge(int numberOfSeconds)

This method is also useful for deleting a cookie - which is achieved by setting a cookie's maximum age value to 0. Any matching cookie on the client will be deleted when this cookie is sent from the server to the client.

The default value is -1. This value means that the cookie will persist until the browser is closed and is then deleted.

 

How to retrieve a cookie and get it's information

Clients return cookies as fields added to HTTP request headers. To retrieve any cookie, you must first retrieve all the cookies using the getCookies method of the HttpServletRequest class.

The getCookies method returns an array of Cookie objects, which you can then search to find the cookie or cookies that you are interested in. Be careful: array will be null if there are no cookies. Remember that multiple cookies can have the same name. To get the name of a cookie, use its getName method. To get the value, use its getValue method.

Thus, the 3 steps are :

  1. Retrieve all the cookies from the user's request - only cookies previously sent by this particular server will be received
     
  2. Find the cookie or cookies with the name that you are interested in, using standard programming techniques
     
  3. Get the values of the cookies that you found


Here is an example :

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

...

// Handle any pending deletes from the shopping cart

String bookId = request.getParameter("Remove");

...

if (bookId != null) {

// Update the shopping cart (not shown)

...

// Update cookies

// Find the cookie(s) that pertains to that book, if any

Cookie[ ] cookies = request.getCookies();

if (cookies != null) {

for (int i=0; i < cookies.length; i++) {

// search through the cookie array

Cookie thisCookie = cookie[i];

if (thisCookie.getName().equals("Buy") && thisCookie.getValue().equals(bookId)) {

// Prepare to delete the cookie by setting its maximum age to zero

thisCookie.setMaxAge(0);

response.addCookie(thisCookie);

// and send it back to be deleted on client

}

}

}

}

// Set the response content type header before accessing the Writer

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//Print out the response

out.println("<html><head><title>Your Shopping Cart</title></head><body><p>..." + ...);

...

}

 

Return to Servlet index