8.5 Basic Cookie Utilities
This section presents some simple but useful utilities for dealing with cookies.
Finding Cookies with Specified Names
Listing 8.3 shows a section of ServletUtilities.java that simplifies the retrieval of a cookie or cookie value, given a cookie name. The getCookieValue method loops through the array of available Cookie objects, returning the value of any Cookie whose name matches the input. If there is no match, the designated default value is returned. So, for example, my typical approach for dealing with cookies is as follows:
Cookie[] cookies = request.getCookies(); String color = ServletUtilities.getCookieValue(cookies, "color", "black"); String font = ServletUtilities.getCookieValue(cookies, "font", "Arial");
The getCookie method also loops through the array comparing names, but returns the actual Cookie object instead of just the value. That method is for cases when you want to do something with the Cookie other than just read its value.
Listing 8.3 ServletUtilities.java
package coreservlets; import javax.servlet.*; import javax.servlet.http.*; public class ServletUtilities { // Other methods in this class shown in earlier chapters. public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie.getValue()); } return(defaultValue); } public static Cookie getCookie(Cookie[] cookies, String cookieName) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie); } return(null); } }
Creating Long-Lived Cookies
Listing 8.4 shows a small class that you can use instead of Cookie if you want your cookie to automatically persist when the client quits the browser. See Listing 8.5 for a servlet that uses this class.
Listing 8.4 LongLivedCookie.java
package coreservlets; import javax.servlet.http.*; /** Cookie that persists 1 year. Default Cookie doesn't * persist past current session. */ public class LongLivedCookie extends Cookie { public static final int SECONDS_PER_YEAR = 60*60*24*365; public LongLivedCookie(String name, String value) { super(name, value); setMaxAge(SECONDS_PER_YEAR); } }