How to Handle Cookies in Servlet?

The HttpServletResponse class allows us to call addCookie method to add a cookie in the response header. The cookie is added to Set-Cookie reponse header.

The setMaxAge method used to specify the maximum age of the cookie in seconds: A positive value of an integer parameter indicates that the cookie will expire after that many seconds have passed; if negative, means the cookie is not stored; if zero, deletes the cookie. Here are code to handle setting a cookie value and deleting a cookie.

    public static void setCookieValue(
HttpServletResponse response, String name, String value, int maxAge)
Cookie cookie = new Cookie(name, value);
public static void deleteCookieValue(HttpServletResponse response, String name)
setCookieValue(response, name, null, 0);

The HttpServletRequest provides getCookies method to us. The method returns an array of Cookie objects. The following code loops through the array of available Cookie objects, returning the value of any Cookie whose name matches the input. If there is no match, the null value is returned:

    public static String getCookieValue(HttpServletRequest request,
 String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie != null && name.equals(cookie.getName())) {
return cookie.getValue();
return null;

Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |