English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Cookie Handling

Cookies are text files stored on the client computer and retain various tracking information. Java Servlet obviously supports HTTP Cookies.

Identifying the returned user includes three steps:

  • The server script sends a set of Cookies to the browser. For example: name, age, or identification number, etc.

  • The browser stores this information on the local computer for future use.

  • When the browser sends any request to the web server next time, it will send these Cookie information to the server, and the server will use this information to identify the user.

This chapter will explain how to set or reset Cookies, how to access them, and how to delete them.

Servlet Cookie processing requires encoding and decoding of Chinese characters, the method is as follows:

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

Cookie Analysis

Cookies are usually set in the HTTP header information (although JavaScript can also set a Cookie directly in the browser). The Servlet that sets the Cookie will send the following header information:

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=oldtoolbag.com
Connection: close
Content-Type: text/html

As you can see, Set-The Cookie header contains 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 that tells the browser to 'forget' the Cookie after the specified time and date.

If the browser is configured to store Cookies, it will retain this information until the expiration date. If the user's browser points to any page that matches the path and domain of the Cookie, it will resend the Cookie to the server. The browser's header information may 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

Servlet can access the request method request.getCookies() Access Cookie, this method will return a Cookie an array of objects.

Servlet Cookie Methods

The following is a list of useful methods that can be used when operating Cookie in Servlet.

Serial NumberMethod & Description
1public void setDomain(String pattern)
This method sets the domain that the cookie is applicable to, for example, oldtoolbag.com.
2public String getDomain()
This method gets the domain that the cookie is applicable to, for example, oldtoolbag.com.
3public void setMaxAge(int expiry)
This method sets the expiration time of the cookie (in seconds). If not set this way, the cookie will only be valid in the current session.
4public int getMaxAge()
This method returns the maximum lifetime of the cookie (in seconds), by default,-1 Indicates that the cookie will last until the browser is closed.
5public String getName()
This method returns the name of the cookie. The name cannot be changed after it is created.
6public void setValue(String newValue)
This method sets the value associated with the cookie.
7public String getValue()
This method gets the value associated with the cookie.
8public void setPath(String uri)
This method sets the path that the cookie is applicable to. If you do not specify a path, all URLs under the same directory as the current page (including subdirectories) will return the cookie.
9public String getPath()
This method gets the path that the cookie is applicable to.
10public void setSecure(boolean flag)
This method sets a boolean value indicating whether the cookie should only be sent over an encrypted (i.e., SSL) connection.
11public void setComment(String purpose)
Set the comment of the cookie. This comment is very useful when the browser presents the cookie to the user.
12public String getComment()
Get the comment of the cookie, if the cookie has no comment, return null.

To set a Cookie through Servlet

There are three steps to set a Cookie through Servlet:

(1) To create a Cookie object:You can call the Cookie constructor with a cookie name and a 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) to set the maximum survival cycle:You can use the setMaxAge method to specify the time (in seconds) that the cookie can remain valid. The following will set the maximum validity period to 24 hour cookie.

cookie.setMaxAge(60*60*24);

(3) to send a Cookie to the HTTP response header:You can use response.addCookie to add Cookies in the HTTP response headers as follows:

response.addCookie(cookie);

Online Example

Let's modify our Form data exampleSet Cookie for the first name and last name.

package com.w3codebox.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 a Cookie for the first name and last name      
        Cookie name = new Cookie("name",
                URLEncoder.encode(request.getParameter("name"), "UTF-8-8")); // Chinese encoding
        Cookie url = new Cookie("url",
                      request.getParameter("url"));
        
        // Set the expiration date for the two Cookies to 24 hours later
        name.setMaxAge(60*60*24); 
        url.setMaxAge(60*60*24); 
        
        // In the response headers, add two Cookies
        response.addCookie( name );
        response.addCookie( url );
        
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        String title = "设置 Cookie 示例";
        String docType = "<!DOCTYPE html>\n"
        out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>站点名:</b>:"
                + request.getParameter("name") + "\n</li>" +
                "  <li><b>站点 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 HelloFormand create the appropriate entry in the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- class name -->  
    <servlet-name>HelloForm</servlet-name>
    <!-- the package where -->
    <servlet-class>com.w3codebox.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <!-- The website to visit -->
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>

Finally, try the following HTML page to call the Servlet.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Tutorial Website(oldtoolbag.com)</title>/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 a file /TomcatTest/test.html.

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

After clicking the "Submit" button, the effect is as follows:

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

Reading Cookie through Servlet

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

Online Example

Let's read the Cookie set in the above example

package com.w3codebox.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;
        // 获取与该域相关的 Cookie 的数组
        cookies = request.getCookies();
         
         // 设置响应内容类型
         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 +
                   "<body bgcolor=\"#f0f0f0\">\n"
          if( cookies != null ){
            out.println("<h2>Cookie 名称和值</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("已删除的 cookie:") + 
                                 cookie.getName() + "<br}}/>
               }
               out.print("Parameter name: " + cookie.getName() + ",
               out.print("Parameter value: " +  URLDecoder.decode(cookie.getValue(), "utf-8) +"<br/>
            }
         }else{
             out.println(
               "<h2 class="tutheader">No Cookie 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 Servlet ReadCookies, and create the appropriate entry in the web.xml file. Try running http://localhost:8080/TomcatTest/ReadCookiesThe following result will be displayed:


Delete Cookie through Servlet

Deleting a cookie is very simple. If you want to delete a cookie, you just need to follow the following three steps:

  • Read an existing cookie and store it in a Cookie object.

  • Use setMaxAge() The method sets the age of the cookie to zero to delete the existing cookie.

  • Add this cookie to the response header.

Online Example

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

package com.w3codebox.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;
        // 获取与该域相关的 Cookie 的数组
        cookies = request.getCookies();
        
            // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
   
        PrintWriter out = response.getWriter();
        String title = "删除 Cookie 示例"
        String docType = "<!DOCTYPE html>\n"
        out.println(docType +
                  "<html>\n" +
                  "<head><title>" + title + "</title></head>\n +
                  "<body bgcolor=\"#f0f0f0\">\n"
         if( cookies != null ){
           out.println("<h2>Cookie 名称和值</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("已删除的 cookie:") + 
                                cookie.getName() + "<br}}/>
              }
              out.print("Parameter name: " + cookie.getName() + ",
              out.print("Parameter value: " + cookie.getValue()+"<br/>
           }
        }else{
            out.println(
              "<h2 class="tutheader">No Cookie 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 Servlet DeleteCookiesCreate an appropriate entry in the web.xml file. Now run http://localhost:8080/TomcatTest/DeleteCookiesThe following result will be displayed: