Java has an abundance of methods for handling cookies. Given a HttpServletRequest one can use the useful getCookies() method.
This method returns an array of cookie objects.
The bare essentials:
public static String getCookieValue(HttpServletRequest request, String name)
{
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies)
{
if (cookie.getName().equals(name))
return cookie.getValue();
}
return "";
}
The below code shows this would work in a Utils method:
/**
* Gets cookie value based for a given cookie name.
*
* @param request the actual HttpServletRequest object which holds the request header information.
* @param name a string for the name of the cookie been requested.
* @return Either an empty string if no such cookie is found or the actual value of the cookie.
* @throws IllegalAccessException
*/
public static String getCookieValue(HttpServletRequest request, String name) throws IllegalAccessException
{
// Be good check your parameters first.
if (request != null && name != null && !name.equals(""))
{
// Here we return all cookie object. If no cookie was set then will be an empty array.
Cookie[] cookies = request.getCookies();
// Loop through each cookie.
for (Cookie cookie : cookies)
{
if (cookie.getName().equals(name))
{
// Return value if the name is matched.
return cookie.getValue();
}
}
}
else
{
// Incorrect parameter list.
throw new IllegalArgumentException();
}
// I will be doing another post on Log4J logger; you can live without this just print to the console.
logger.warn("No such cookie with name:"+name+" returned empty string by default.");
return "";
}
One caveat is if you are using an IDE to test this code most IDEs (as Eclipse did) will ignore any system classpath, and rely on project-specific settings. You will need to add external JARs to your project path.

Leave a comment