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"); ...

Get Core Servlets and JavaServer Pages™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.