2.2 Get information from a cookie

In previous example, we have created a servlet that create and send cookie to the browser. Now, discuss in details:

A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value.

Cookie cookie = new Cookie("user","uid1234");

The Cookie class provides a number of methods for setting a cookie's values and attributes.  You can set the cookie expiration time via the setMaxAge(int expiry) method. This method sets the maximum age in seconds for this Cookie.

A positive value indicates that the cookie will expire after that many seconds have passed. A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. The following cookie expires after one hour.

cookie.setMaxAge(60*60);

The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse. Here's an example:

response.addCookie(cookie);


To get information from a cookie

To retrieve any cookie, you must retrieve all the cookies using the getCookies method of the HttpServletRequest class.

The getCookies method returns an array of Cookie objects, which you can search to find the cookie that you want.

Cookie[] cookies = request.getCookies();
if (cookies != null) 
{
  for (Cookie cookie : cookies)
  {
    String name = cookie.getName();
    String value = cookie.getValue();
  }
}

Following program uses a "cookie" to identify new vs. repeat visitor to the site. If visitor is newcomer it will display, 'Welcome!!' otherwise display 'Welcome back!!'.

package com.beginwithjava.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/Greeting")
public class GreetVisitor extends HttpServlet 
{       
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        // obtain a list of cookies
        Cookie[] cookies = request.getCookies();
        
        boolean newVisit = true;
        
        //If the request contains cookies
        if (cookies != null)
        {
          // Find the cookie of interest in arrays of cookies
          for (Cookie cookie : cookies)
          {
             if (cookie.getName().equals("repeat") &&
                  (cookie.getValue().equals("yes"))) 
             {
                  newVisit = false;
                  break;
             }
          }
        }
        // for the first time visit
        else
        {
            // create a cookie
            Cookie cookie = new Cookie( "repeat", "yes");
            //Setting the maximum age to 1 year
            cookie.setMaxAge(60*60*24*365);
            //Send the cookie to the browser
            response.addCookie(cookie);
        }
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        if(newVisit)
            out.println("Welcome!!");
        else
            out.println("Welcome back!!");
    }
}