Recipe 10.2 Creating an Array from All of the Request s Cookies


Recipe 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 Cookie s 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 Cookie s 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 a JSP; Recipe 10.4 on using a servlet to read cookies; Recipe 10.5 on reading cookie values with a JSP; Recipe 10.6 on altering or removing an existing cookie; the RFC 2109 document dealing with cookies: ftp://ftp.rfc-editor.org/in-notes/rfc2109.txt; Netscape's preliminary specification for cookies: http://wp.netscape.com/newsref/std/cookie_spec.html; the Java Cookie API: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/Cookie.html.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net