O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

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

10.4. Reading Cookie Values with a Servlet

Problem

You want to read cookie values from a client using a servlet.

Solution

Create a Java array of javax.servlet.http.Cookie objects by calling the HttpServletRequest.getCookies( ) method. Then cycle through the array, accessing each cookie and value as needed.

Discussion

The web user will send cookies to a web site only if the user originally received Set-Cookie headers from that domain. In addition, if the cookie was set with a Path attribute specifying a context path, then the servlet can access the cookie only if the servlet is also associated with the context path. As a result, always test the return value of the request.getCookies( ) method (which returns an array of Cookie objects) to see if it is null, indicating that the user has not sent any cookies, before operating upon it.

Example 10-5 displays the value of any found cookies in a web browser. The CookieReader class uses the javax.servlet.http.Cookie.getName( ) and getValue( ) methods in order to display this information.

Example 10-5. A cookie-reading servlet

package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class CookieReader extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException,
    java.io.IOException {
    
      Cookie cookie = null;//Get an array of Cookies associated with this domain
      Cookie[] cookies = request.getCookies( );
      boolean hasCookies = false;
    
      //if cookies contains ...

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