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.2. Creating an Array from All of the Request's Cookies

Problem

You want to store all of the cookies contained by a client's request in a Cookie array.

Solution

Use the HttpServletRequest.getCookies( ) method, which returns an array of javax.servlet.http.Cookie objects.

Discussion

To create an array of Cookies representing all of the cookies included in a request, use the HttpServletRequest.getCookies( ) method. You can then access the name and value of a cookie by calling the Cookie class's getName( ) and getValue( ) methods.

The code for accessing an array of Cookies looks like Example 10-2.

Example 10-2. Creating a Cookie array

//servlet's doGet method

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( );

    //Check for a null value, then do something with any Cookies
    if (cookies != null){ //read each Cookie value 
    }
//rest of the servlet

Once a cookie has already been created, the next time the user sends the cookie as a request header, the only information you can extract from the Cookie object is its name and value. You will not be able to derive the cookie's maximum age from the request header, because all the header will contain is the Cookie object: header name, then the name and value of the cookie.

See Also

Recipe 10.1 on setting a cookie with a servlet; Recipe 10.3 on setting a cookie with ...

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