3.1 Cookies

Cookies are small text information that a Web server sends to a browser and the browser stores it locally. When you visit the same website in future, browser returns unchanged data to the server.

Web sites use cookies in many different ways. Here are some of the most common examples:

  • Cookies are a convenient way to carry information from one session to another on a website. This capability is so useful that servlets have an API for session tracking, and servlet and JSP authors don't need to manipulate cookies directly.
  • Avoiding username and password. Many large sites require you to register in order to use their services, but it is inconvenient to remember the username and password. Cookies are a good alternative for low-security sites. When a user registers, a cookie is sent with a unique user ID. When the client reconnects at a later date, the user ID is returned, the server looks it up, determines it belongs to a registered user, and doesn't require an explicit username and password.
  • Sites can accurately determine how many people actually visit the site. The only way for a site to accurately count visitors is to set a cookie with a unique ID for each visitor. Using cookies, sites can determine how many visitors arrive, how many are new versus repeat visitors and how often a visitor has visited. Sites can store user preferences so that the site can look different for each visitor (often referred to as customization).

A simple cookie example in servlet

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("/CookieDemo")
public class CookieDemo extends HttpServlet 
{       
    public void doGet(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, IOException 
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        //Creating a cookie object.
        Cookie cookie = new Cookie("user","uid1234");
        
        //Setting the maximum age to 1 hour
        cookie.setMaxAge(60*60);
        
        //Send the cookie to the client
        response.addCookie(cookie);
        
        out.println("Cookie created");
    }
}

When you run this servlet using Google Chrome. Your brower will store the cookie object. To see cookie content follow these steps :
1. In the top right of Google Chrome, click the Menu.
2. Click Settings and then Show advanced settings.
3. In the "Privacy" section, click Content settings.
4. Under "Cookies," click All cookies and site data.
5. Click on localhost

cookie