JSP cookie handling


Cookies are text files stored on the client computer. They save a large amount of track information. Based on servlet technology, JSP can obviously provide support for HTTP cookies.

There are usually three steps to identify repeat customers:

  •           The server script sends a series of cookies to the browser. Such as name, age, ID number, etc.

  •             The browser stores this information locally on the computer in case it is needed.

  •             The next time the browser sends any request to the server, it will also send these cookie information to the server, and then the server uses this information to identify the user or do other things.

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

JSP Cookie processing requires encoding and decoding Chinese, the method is as follows:

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

Cookie Analysis

Cookies are usually set in HTTP headers (although JavaScript can set cookies directly in the browser). In JSP, setting a cookie requires sending the following information header to the server:

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

As you can see, the Set-Cookie information header contains a key-value pair, a GMT (Greenwich Mean Time) time, and a path. a domain name. Key-value pairs will be encoded as URLs. The expiry date field is an instruction that tells the browser after which time the cookie can be cleared.

If the browser is configured to store cookies, it will save this information until it expires. If any page visited by the user matches the path and domain name in the cookie, the browser will re-send the cookie back to the server. The information header on the browser side looks like the following:

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 JSP script accesses these cookies through the getCookies() method in the request object. This method returns an array of Cookie objects.


Servlet Cookie methods

The following table lists the commonly used methods in Cookie objects:

##                 5                 6             7             8##                 9public String getPath()             10public void setSecure(boolean flag)             11public void setComment(String purpose)             12public String getComment()

Setting Cookie using JSP

Setting cookie using JSP involves three steps:

(1) Create a Cookie object: Call the Cookie constructor , using a cookie name and value as parameters, both of which are strings.

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

Please remember that neither the name nor the value can contain spaces or the following characters:

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

(2) Set the validity period: Call the setMaxAge() function to indicate the cookie How long (in seconds) it is valid for. The following operation sets the validity period to 24 hours.

cookie.setMaxAge(60*60*24);

(3) Send cookie to HTTP response header: Call response.addCookie() function to add cookie to HTTP response header.

response.addCookie(cookie);

Example demonstration

The main.jsp file code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<%
   // 编码,解决中文乱码   
   String str = URLEncoder.encode(request.getParameter("name"),"utf-8");  
   // 设置 name 和 url cookie 
   Cookie name = new Cookie("name",
		   str);
   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 );
%>
<html>
<head>
<title>设置 Cookie</title>
</head>
<body>

<h1>设置 Cookie</h1>

<ul>
<li><p><b>网站名:</b>
   <%= request.getParameter("name")%>
</p></li>
<li><p><b>网址:</b>
   <%= request.getParameter("url")%>
</p></li>
</ul>
</body>
</html>

The following is a simple HTML form that submits client data to the main.jsp file, and set cookies:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>

<form action="main.jsp" method=GET>
站点名: <input type="text" name="name">
<br />
网址: <input type="text" name="url" />
<input type="submit" value="提交" />
</form>

</body>
</html>

Save the above HTML code to the test.htm file.

Place this file in the WebContent directory of the current jsp project (the same directory as main.jsp).

Submit the form data to the main.jsp file by visiting http://localhost:8080/testjsp/test.html. The demonstration Gif image is as follows:

Try to enter "site name" and "web address", and then click the submit button, it will display "site name" and "web address" in your screen, and set both "site name" and "web address" cookies.


Reading Cookies using JSP

To read cookies, you need to call the request.getCookies() method to obtain an array of javax.servlet.http.Cookie objects. Then iterate through this array and use the getName() method and getValue() method to get the name and value of each cookie.

<h3 Example Demonstration< h3="">

Let us read the cookie in the previous example. The following is the cookie.jsp file code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>获取 Cookie</title>
</head>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // 获取cookies的数据,是一个数组
   cookies = request.getCookies();
   if( cookies != null ){
      out.println("<h2> 查找 Cookie 名与值</h2>");
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
        
         out.print("参数名 : " + cookie.getName());
         out.print("<br>");
         out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br>");
         out.print("------------------------------------<br>");
      }
  }else{
      out.println("<h2>没有发现 Cookie</h2>");
  }
%>
</body>
</html>

After browser access , the output result is:

C6A7341F-029A-4244-8B38-BE010E391091.jpg


Deleting Cookies using JSP

Deleting cookies is very simple. If you want to delete a cookie, just follow the steps given below:

  •             Get an existing cookie and store it in the Cookie object.

  •             Set the cookie expiry date to 0.

  •             Add this cookie back to the response header.


Example demonstration

The following program deletes a cookie named "name". When you run cookie.jsp for the second time, name will is null.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>获取 Cookie</title>
</head>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   // 获取当前域名下的cookies,是一个数组
   cookies = request.getCookies();
   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("<br>");
         out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br>");
         out.print("------------------------------------<br>");
      }
  }else{
	  out.println("<h2>没有发现 Cookie</h2>");
  }
%>
</body>
</html>

Access through the browser, the output result is:

C6A7341F-029A-4244-8B38-BE010E391091.jpg

Visit http://localhost:8080/testjsp/cookie.jsp again, you will get the following results:

7BF1C669-F7A4-4245-B7B0-B79BBB272604.jpg

You can see that the cookie named width="70%" "name" has disappeared.

You can also manually delete cookies in your browser. In the IE browser, you can delete all cookies by clicking the Tools menu item, then selecting Internet Options, and clicking Delete Cookies.

Serial numberMethod & Description
              1public void setDomain(String pattern)


Set the domain name of the cookie, such as w3cschool.cc
                2public String getDomain()


Get the domain name of the cookie, such as w3cschool.cc
                3public void setMaxAge(int expiry)


Set the cookie validity period in seconds. The default validity period is the survival time of the current session
                4public int getMaxAge()


Get the cookie validity period, in seconds, the default is -1, indicating that the cookie will live until the browser is closed
public String getName()


Returns the name of the cookie. The name cannot be modified after it is created.

public void setValue(String newValue)


Set the cookie value

public String getValue()


Get the value of cookie

public void setPath(String uri)


Set the cookie path, which defaults to all URLs in the current page directory, as well as all subdirectories in this directory

Get the path of the cookie

Indicate whether the cookie should be encrypted for transmission

Set a comment describing the purpose of the cookie. Comments will become very useful when the browser displays the cookie to the user

Returns a comment describing the purpose of the cookie, or null if none