Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet cookies are processed


May 14, 2021 Servlet


Table of contents


Servlet cookies are processed

Cookies are text files stored on client computers and retain various tracking information. Java Servlet clearly supports HTTP cookies.

Identifying the returning user consists of three steps:

  • The server script sends a set of cookies to the browser. For example: name, age, identification number, etc.
  • The browser stores this information on the local computer for future use.
  • The next time the browser sends any request to the web server, the browser sends these cookies to the server, which the server uses to identify the user.

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

Servlet cookie processing requires Chinese decoding and decoding of the data in the following ways:

String   str   =   java.net.URLEncoder.encode("中文");            //编码
String   str   =   java.net.URLDecoder.decode("编码后的字符串");   // 解码

Cookie profiling

Cookies are usually set in HTTP header information (although JavaScript can also set a cookie directly on the browser). The servlet that sets the cookie sends the following header message:

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

As you can see, the Set-Cookie header contains a pair of name values, a GMT date, a path, and a domain. T he name and value are encoded by the URL. The expires field is an instruction that tells the browser to "forget" the cookie after a given time and date.

If the browser is configured to store cookies, it retains this information until the expiration date. I f the user's browser points to any page that matches the path and domain of the cookie, it resends the cookie to the server. The browser's header information 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

Servlet is able to access cookies through the request method request.getCookies(), which returns an array of cookie objects.

Servlet cookies method

The following is a list of useful ways to manipulate cookies in a servlet.

Serial number Method & Description
1 public void setDomain(String pattern)
This method sets the available domain for cookies, such as W3CSChool.cn.
2 public String getDomain()
This method obtains a cookie applicable domain, such as W3CSChool.cn.
3 public void setMaxAge(int expiry)
This method sets the time (in seconds) of the cookie.If you don't set it, cookies will only be valid in the current session session.
4 public int getMaxAge()
This method returns the maximum survival period of cookie (in seconds). By default, -1 indicates that cookies will continue until the browser off.
5 public String getName()
This method returns the name of the cookie.The name cannot be changed after being created.
6 public void setValue(String newValue)
This method sets the value associated with the cookie.
7 public String getValue()
This method gets the value associated with the cookie.
8 public void setPath(String uri)
This method sets the path to cookies.If you don't specify a path, all URLs under the same directory as the current page (including subdirectory) will return cookies.
9 public String getPath()
This method obtains the path to the cookie.
10 public void setSecure(boolean flag)
This method sets the Boolean value, indicating whether the cookie should only be sent only on the encrypted (ie SSL) connection.
11 public void setComment(String purpose)
This method specifies a comment describing the cookie purpose.This comment is useful when the browser presents cookies to the user.
12 public String getComment()
This method returns a comment describing the cookie purpose, and returns NULL if the cookie is not commented.

Set cookies with the servlet

Setting cookies with servlets consists of three steps:

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

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

Keep in mind that neither the name nor the value should contain spaces or any of the following characters:

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

(2) Set a maximum lifetime: You can use the setMaxAge method to specify when cookies can remain valid in seconds. A cookie with a maximum validity of 24 hours will be set below.

cookie.setMaxAge(60*60*24); 

(3) Send cookies to the HTTP response header: You can use the response.add cookie to add cookies in the HTTP response header, as follows:

response.addCookie(cookie);

Let's modify our form data instance to set cookies for first and last names.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// 扩展 HttpServlet 类
public class HelloForm extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 为名字和姓氏创建 Cookies      
      Cookie firstName = new Cookie("first_name",
                      request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name",
                      request.getParameter("last_name"));

      // 为两个 Cookies 设置过期日期为 24 小时后
      firstName.setMaxAge(60*60*24); 
      lastName.setMaxAge(60*60*24); 

      // 在响应头中添加两个 Cookies
      response.addCookie( firstName );
      response.addCookie( lastName );

      // 设置响应内容类型
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "设置 Cookies 实例";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\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("first_name") + "\n" +
                "  <li><b>姓氏</b>:"
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}

Compile the Servlet HelloForm above and create the appropriate entry .xml the web server file, and finally try the HTML page below to call the Servlet.

 
<html>
<body>
<form action="HelloForm" method="GET">
名字:<input type="text" name="first_name">
<br />
姓氏:<input type="text" name="last_name" />
<input type="submit" value="提交" />
</form>
</body>
</html>

Save the HTML content above to the file hello .htm and place it in the directory of the .lt;Tomcat-design-directory/webapps/ROOT. When you access http://localhost:8080/Hello.htm, the actual output of the form above looks like this:

Servlet cookies are processed

Try entering your first and last name, then click the Submit button, and the first and last name will appear on the screen, setting up both firstName and lastName cookies, which will be sent back to the server the next time you press the submit button.

The next section explains how to access these cookies in a web application.

Read cookies through servlets

To read cookies, you need to create an array of javax.servlet.http://www.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 associated value.

Let's read the cookies set in the instance above

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// 扩展 HttpServlet 类
public class ReadCookies extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      Cookie cookie = null;
    Cookie[] cookies = null;
      // 获取与该域相关的 Cookies 的数组
      cookies = request.getCookies();
      
    // 设置响应内容类型
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Reading Cookies Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" );
      if( cookies != null ){
         out.println("<h2>查找 Cookies 名称和值</h2>");
         for (int i = 0; i < cookies.length; i++){             cookie = cookies[i];             out.print("名称:" + cookie.getName( ) + ",");             out.print("值:" + cookie.getValue( )+" <br/>");
         }
      }else{
          out.println(
            "<h2 class="tutheader">未找到 Cookies</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

Compile the Servlet Read Cookies above and create the appropriate entries .xml the web page file. If you have set the first_name cookie to "John" and last_name cookie to "Player" and try to run http://localhost:8080/ReadCookies, the following results will be displayed:

Look for cookies name and value

Name: first_name, Value: John
Name: last_name, Value: Player

Remove cookies from the servlet

Removing cookies is very simple. If you want to delete a cookie, you only need to follow these three steps:

  • Read an existing cookie and store it in the cookie object.
  • Use the setMaxAge() method to set the age of the cookie to zero to remove an existing cookie.
  • Add this cookie to the response header.

The following example removes an existing first_name named "first_name" and returns an empty value the next time you run the Servlet first_name ReadCookies.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// 扩展 HttpServlet 类
public class DeleteCookies extends HttpServlet {
 
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      Cookie cookie = null;
    Cookie[] cookies = null;
      // 获取与该域相关的 Cookies 的数组
      cookies = request.getCookies();
      
    // 设置响应内容类型
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "Delete Cookies Example";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" );
       if( cookies != null ){
         out.println("<h2>Cookies 名称和值</h2>");
         for (int i = 0; i < cookies.length; i++){             cookie = cookies[i];             if((cookie.getName( )).compareTo("first_name") == 0 ){                  cookie.setMaxAge(0);                  response.addCookie(cookie);                  out.print("已删除的 cookie:" +                                cookie.getName( ) + "<br/>");
            }
            out.print("名称:" + cookie.getName( ) + ",");
            out.print("值:" + cookie.getValue( )+" <br/>");
         }
      }else{
          out.println(
            "<h2 class="tutheader">No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

Compile the Servlet Delete Cookie above and create the appropriate entry .xml the web server file. Now run the http://localhost:8080/DeleteCookies and the following results will be displayed:

Cookies name and value

Deleted cookies: First_name
Name: first_name, Value: John
Name: last_name, Value: Player

Now try running http://localhost:8080/ReadCookies, which will display only one cookie, as follows:

Look for cookies name and value

Name: last_name, Value: Player

You can manually remove cookies from Internet Explorer. I n the Tools menu, select Internet Options. If you want to delete all cookies, press Delete cookies.