Question

How do I read browser cookies from a servlet?

Answer

Reading cookies from a servlet is quite easy. You can gain access to any cookies sent by the browser from the javax.servlet.http.HttpServletRequest passed to the servlet's doGet, doPost, etc methods. HttpServletResponse offers a method, Cookies[] getCookies() which returns an array of Cookie objects. However, if no cookies are available, this value may be null, so be sure to check before accessing any array elements.

// Check for cookies
Cookie[] cookie_jar = request.getCookies();

// Check to see if any cookies exists
if (cookie_jar != null)
{
	for (int i =0; i< cookies.length; i++)
	{
		Cookie aCookie = cookie_jar[i];
		pout.println ("Name : " + aCookie.getName());
		pout.println ("Value: " + aCookie.getValue());
	}
}


Back