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!
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.