Latest web development tutorials

Servlet Cookie Processing

Cookie is a text file stored on the client computer, and retains a variety of tracking information. Java Servlet clearly support HTTP Cookie.

Returns the user identification involves three steps:

  • Server script sends a Cookie to the browser. For example: name, age or identification number.
  • The browser will store this information on the local computer for future use.
  • The next time the browser sends a request to any Web server, the browser will send the Cookie information to the server, the server will use this information to identify users.

This chapter tells you how to set or reset Cookie, how to access them, and how to remove them.

Servlet Cookie processing needs of Chinese encode and decode, as follows:

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

Cookie Analysis

Cookie is usually set in the HTTP header information (although JavaScript can also be set directly in a browser Cookie). Setting the Servlet Cookie will send the following header:

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

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

If your browser is configured to store Cookie, it will retain this information until the expiration date. If the user's browser to match any of the Cookie domain and path of the page, it will re-send the Cookie to the server. Browser header information may appear as follows:

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 by Cookie request methodrequest.getCookies (),which returns an array ofCookieobjects.

Servlet Cookie Methods

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

序号方法 & 描述
1public void setDomain(String pattern)
该方法设置 cookie 适用的域,例如 w3cschool.cc。
2public String getDomain()
该方法获取 cookie 适用的域,例如 w3cschool.cc。
3public void setMaxAge(int expiry)
该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中持续有效。
4public int getMaxAge()
该方法返回 cookie 的最大生存周期(以秒为单位),默认情况下,-1 表示 cookie 将持续下去,直到浏览器关闭。
5public String getName()
该方法返回 cookie 的名称。名称在创建后不能改变。
6public void setValue(String newValue)
该方法设置与 cookie 关联的值。
7public String getValue()
该方法获取与 cookie 关联的值。
8public void setPath(String uri)
该方法设置 cookie 适用的路径。如果您不指定路径,与当前页面相同目录下的(包括子目录下的)所有 URL 都会返回 cookie。
9public String getPath()
该方法获取 cookie 适用的路径。
10public void setSecure(boolean flag)
该方法设置布尔值,表示 cookie 是否应该只在加密的(即 SSL)连接上发送。
11public void setComment(String purpose)
设置cookie的注释。该注释在浏览器向用户呈现 cookie 时非常有用。
12public String getComment()
获取 cookie 的注释,如果 cookie 没有注释则返回 null。

Cookie settings through Servlet

By setting Servlet Cookie involves three steps:

(1) Create a Cookie object: You can call the Cookie constructor with a cookie name and cookie value, cookie name and cookie values are strings.

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

Remember, regardless of the name or value, should not contain any spaces or the following characters:

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

(2) set the maximum lifetime: You can use the method to specify cookie setMaxAge able to maintain a valid time (in seconds).We will set a maximum validity of 24 hours a cookie.

cookie.setMaxAge(60*60*24); 

(3) to send Cookie HTTP response headers: You can use response.addCookieto add HTTP response header Cookie, as follows:

response.addCookie(cookie);

Examples

Let's modify our form data instances , set the Cookie of first and last names.

package com.w3big.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
	{
		// 为名字和姓氏创建 Cookie      
		Cookie name = new Cookie("name",
				URLEncoder.encode(request.getParameter("name"), "UTF-8")); // 中文转码
		Cookie url = new Cookie("url",
		              request.getParameter("url"));
		
		// 为两个 Cookie 设置过期日期为 24 小时后
		name.setMaxAge(60*60*24); 
		url.setMaxAge(60*60*24); 
		
		// 在响应头中添加两个 Cookie
		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 previousServlet HelloForm, and create the appropriate entry in the web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet> 
    <!-- 类名 -->  
    <servlet-name>HelloForm</servlet-name>
    <!-- 所在的包 -->
    <servlet-class>com.w3big.test.HelloForm</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HelloForm</servlet-name>
    <!-- 访问的网址 -->
    <url-pattern>/TomcatTest/HelloForm</url-pattern>
  </servlet-mapping>
</web-app>
The last attempt to call the following HTML page Servlet.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</title>
</head>
<body>
<form action=/TomcatTest/HelloForm method="GET">
站点名 :<input type="text" name="name">
<br />
站点 URL:<input type="text" name="url" /><br>
<input type="submit" value="提交" />
</form>
</body>
</html>

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

Next we visit http: // localhost: 8080 / TomcatTest / test.html, Gif demo as follows:

Note: Some of the above path requires more actual path modify your project.

Read through Servlet Cookie

To read Cookie, you need to create ajavax.servlet.http.Cookieobject by callingthe HttpServletRequestgetCookies () method array. Then loop through the array and uses getName () and getValue () method to access the value of each cookie and associated.

Examples

Cookie Let's read the above example set

package com.w3big.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("名称:" + cookie.getName( ) + ",");
               out.print("值:" +  URLDecoder.decode(cookie.getValue(), "utf-8") +" <br/>");
            }
         }else{
             out.println(
               "<h2 class=\"tutheader\">No Cookie founds</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 previousServlet ReadCookies, and create the appropriate entry in the web.xml file.Try to runhttp: // localhost: 8080 / TomcatTest/ HelloForm, will show the following results:


Remove Cookie by Servlet

Remove Cookie is very simple. If you want to delete a cookie, you only need to follow the following three steps:

  • Reads an existing cookie, and store it in a Cookie object.
  • UsesetMaxAge () method to set the cookie's age zero to delete an existing cookie.
  • Add the cookie to the response headers.

Examples

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

package com.w3big.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("名称:" + cookie.getName( ) + ",");
              out.print("值:" + cookie.getValue( )+" <br/>");
           }
        }else{
            out.println(
              "<h2 class=\"tutheader\">No Cookie founds</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 previousServlet DeleteCookies, and create the appropriate entry in the web.xml file.Now runhttp: // localhost: 8080 / TomcatTest/ DeleteCookies, will show the following results: