Easy Tutorial
❮ Servlet Tutorial Servlet Auto Refresh ❯

Servlet Cookie Handling

Cookies are text files stored on the client computer and they hold various tracking information. Java Servlets clearly support HTTP cookies.

Identifying returning users involves three steps:

This chapter will guide you on how to set or reset cookies, how to access them, and how to delete them.

>

Servlet Cookie handling requires encoding and decoding in Chinese, as follows:

String str = java.net.URLEncoder.encode("中文", "UTF-8");            // Encoding
String str = java.net.URLDecoder.decode("Encoded String", "UTF-8");   // Decoding

Cookie Anatomy

Cookies are usually set in the HTTP header (although JavaScript can also set a cookie directly on the browser). A Servlet that sets a cookie sends a header like this:

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=tutorialpro.org
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header includes a name-value pair, a GMT date, a path, and a domain. The name and value are URL-encoded. The expires field is an instruction telling the browser to "forget" the cookie after the given date and time.

If the browser is configured to store cookies, it will keep this information until the expiration date. If the user's browser points to any page that matches the cookie's path and domain, it will resend the cookie to the server. The browser's header might look like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

The Servlet can then access the cookie through the request method request.getCookies(), which returns an array of Cookie objects.

Servlet Cookie Methods

Here is a list of useful methods available in Servlets for handling cookies.

No. Method & Description
1 public void setDomain(String pattern) <br>This method sets the domain to which the cookie applies, for example, tutorialpro.org.
2 public String getDomain() <br>This method gets the domain to which the cookie applies, for example, tutorialpro.org.
3 public void setMaxAge(int expiry) <br>This method sets the maximum age of the cookie in seconds. If not set, the cookie is valid only for the current session.
4 public int getMaxAge() <br>This method returns the maximum age of the cookie in seconds. By default, -1 indicates that the cookie will persist until the browser is closed.
5 public String getName() <br>This method returns the name of the cookie. The name cannot be changed after creation.
6 public void setValue(String newValue) <br>This method sets the value associated with the cookie.
7 public String getValue() <br>This method gets the value associated with the cookie.
8 public void setPath(String uri) <br>This method sets the path for which the cookie is applicable. If you do not specify a path, all URLs in the same directory as the current page (including subdirectories) will return the cookie.
9 public String getPath() <br>This method retrieves the path for which the cookie is applicable.
10 public void setSecure(boolean flag) <br>This method sets a boolean value indicating whether the cookie should only be sent over a secure (i.e., SSL) connection.
11 public void setComment(String purpose) <br>Sets the comment describing the purpose of the cookie. This comment is useful when the browser presents the cookie to the user.
12 public String getComment() <br>Retrieves the comment of the cookie, or returns null if the cookie has no comment.

Setting Cookies with Servlet

Setting cookies with Servlet involves three steps:

(1) Creating a Cookie object: You can call the Cookie constructor with the cookie name and cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Remember that neither the name nor the value should contain spaces or any of the following characters:

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You can use the setMaxAge method to specify the duration for which the cookie remains valid (in seconds). The following sets a cookie with a maximum age of 24 hours.

cookie.setMaxAge(60*60*24);

(3) Sending the Cookie to the HTTP response header: You can use response.addCookie to add the Cookie to the HTTP response header, as shown below:

response.addCookie(cookie);

Example

Let's modify our Form Data Example to set cookies for the first name and last name.

package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

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;

/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Create cookies for first name and last name      
        Cookie name = new Cookie("name",
```java
URLEncoder.encode(request.getParameter("name"), "UTF-8")); // Chinese encoding
Cookie url = new Cookie("url",
              request.getParameter("url"));

// Set expiration date for both cookies to 24 hours later
name.setMaxAge(60*60*24); 
url.setMaxAge(60*60*24); 

// Add both cookies to the response header
response.addCookie(name);
response.addCookie(url);

// Set response content type
response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();
String title = "Setting Cookie Example";
String docType = "<!DOCTYPE html>\n";
out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "&lt;body bgcolor=\"#f0f0f0\">\n" +
        "&lt;h1 align=\"center\">" + title + "</h1>\n" +
        "<ul>\n" +
        "  <li><b>Site Name:</b> "
        + request.getParameter("name") + "\n</li>" +
        "  <li><b>Site URL:</b> "
        + request.getParameter("url") + "\n</li>" +
        "</ul>\n" +
        "</body></html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Compile the above Servlet HelloForm and create the appropriate entries in the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- Class name -->  
    <servlet-name>HelloForm</servlet-name>
    <!-- Package location -->
    <servlet-class>com.tutorialpro.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <!-- URL to access -->
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<form action="/TomcatTest/HelloForm" method="GET">
Site Name: <input type="text" name="name">
<br />
Site URL: <input type="text" name="url" /><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>

Save the above HTML content to the file /TomcatTest/test.html.

Next, we access http://localhost:8080/TomcatTest/test.html, and the GIF demonstration is as follows:

>

Note: Some paths need to be modified according to your actual project path.

Reading Cookies via Servlet

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies() method of HttpServletRequest. Then, loop through the array and use the getName() and getValue() methods to access each cookie and its associated value.

Example

Let's read the cookies set in the above example:

package com.tutorialpro.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

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;

/**
 * Servlet implementation class ReadCookies
 */
@WebServlet("/ReadCookies")
public class ReadCookies extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadCookies() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Cookie cookie = null;
        Cookie[] cookies = null;
        // Get an array of Cookies associated with this domain
        cookies = request.getCookies();

        // Set response content type
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "Delete Cookie Example";
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
                  "<html>\n" +
                  "<head><title>" + title + "</title></head>\n" +
                  "&lt;body bgcolor=\"#f0f0f0\">\n" );
if( cookies != null ){
    out.println("<h2>Cookie Names and Values</h2>");
    for (int i = 0; i < cookies.length; i++){
        cookie = cookies[i];
        if((cookie.getName()).compareTo("name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("Deleted cookie: " + 
                        cookie.getName() + "<br/>");
        }
        out.print("Name: " + cookie.getName() + ", ");
        out.print("Value: " +  URLDecoder.decode(cookie.getValue(), "utf-8") + " <br/>");
    }
}else{
    out.println(
        "&lt;h2 class=\"tutheader\">No Cookies found</h2>");
}
out.println("</body>");
out.println("</html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Compile the above ReadCookies Servlet and create the appropriate entries in the web.xml file. Try running http://localhost:8080/TomcatTest/ReadCookies, which will display the following result:

Deleting a Cookie with Servlet

Deleting a cookie is quite simple. If you want to delete a cookie, then you simply follow these three steps:

Example

The following example will delete an existing cookie named "url", and when you run the ReadCookies Servlet next time, it will return the url as null.

package com.tutorialpro.test;

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;

/**
 * Servlet implementation class DeleteCookies
 */
@WebServlet("/DeleteCookies")
public class DeleteCookies extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
/**
 * @see HttpServlet#HttpServlet()
 */
public DeleteCookies() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Cookie cookie = null;
    Cookie[] cookies = null;
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();

    // Set response content type
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    String title = "Delete Cookie Example";
    String docType = "<!DOCTYPE html>\n";
    out.println(docType +
              "<html>\n" +
              "<head><title>" + title + "</title></head>\n" +
              "&lt;body bgcolor=\"#f0f0f0\">\n");
    if (cookies != null) {
       out.println("<h2>Cookie Names and Values</h2>");
       for (int i = 0; i < cookies.length; i++) {
          cookie = cookies[i];
          if ((cookie.getName()).compareTo("url") == 0) {
               cookie.setMaxAge(0);
               response.addCookie(cookie);
               out.print("Deleted cookie: " + 
                            cookie.getName() + "<br/>");
          }
          out.print("Name: " + cookie.getName() + ", ");
          out.print("Value: " + cookie.getValue() + " <br/>");
       }
    } else {
        out.println(
          "&lt;h2 class=\"tutheader\">No Cookies found</h2>");
    }
    out.println("</body>");
    out.println("</html>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Compile the DeleteCookies Servlet above and create appropriate entries in the web.xml file. Now run http://localhost:8080/TomcatTest/DeleteCookies, and the following result will be displayed:

❮ Servlet Tutorial Servlet Auto Refresh ❯