How do you check for the existence of a cookie?

John Zukowski

Retrieving cookie data is a little awkward. You cannot ask for the cookie with a specific key. You must ask for all cookies and find the specific one you are interested in. And, it is possible that multiple cookies could have the same name, so just finding the first setting is not always sufficient. The following code finds the setting of a single-valued cookie:

int sum = 0;
Cookie theCookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null) {
  for(int i=0, n=cookies.length; i < n; i++) {
    theCookie = cookies[i];
    if (theCookie.getName().equals(SUM_KEY)) {
      try {
        sum = Integer.parseInt(theCookie.getValue());
      } catch (NumberFormatException ignored) {
        sum = 0;