Home  Servlets  Servlet hosting  Servlets intro  Sessions  Cookies  HTTP headers  Status codes  Keep-alive


Threads Database Profiling Regular expressions Random numbers Compression Exceptions C Equivalents in Java
 Comment on this article  List of Java topics

The Java Cookie class: reading cookies

On the previous page, we saw how to set a cookie by creating an instance of the Cookie class and attaching it to an HttpServletResposne object. To read cookies on subequent requests to the Servlet, we query the HttpServletRequest object. To find the cookie that we want, we actually get the list of cookies and cycle through, querying each to check if it matches the name— and possibly other cirteria— that we are looking for:

Cookie[] cookies = req.getCookies();
if (cookies != null)
  for (Cookie ck : cookies) {
    if ("prefResultsPerPage".equals(ck.getName())) {
      String prefValue = ck.getValue();
      ...
    }

This may seem a slightly paradoxical way of fetching the cookie— at first glance, a getCookieByName() method would have seemed more logical. The problem is that it is possible for more than one cookie to have the same name (and, for example, for one to belong to the host as a whole and another to a specific path). Thus, we are left with having to cycle through the cookies sent by the browser for the given URI and picking the one(s) we are interested in, using whatever means we feel appropriate in the case of a double match.

Notice also a subtlty of the above method: if the client sent no cookies, then the getCookies() method can return null!


Written by Neil Coffey. Copyright © Javamex UK 2008. All rights reserved.