Latest web development tutorials

JSP Cookie Processing

Cookie is a text file stored in the client, and they save a lot of track information. In servlet technology basis, JSP apparently be able to provide support for the HTTP cookie.

Typically there are three steps to identify repeat visitors:

  • Server script sends a series of cookie to the browser. Such as name, age, ID number, etc.
  • Browsers store this information on the local machine, to prepare for contingencies.
  • The next time the browser sends any request to the server, it will also be sent to the server the cookie information, and the server uses this information to identify the user or to do some other things.

This chapter will teach you how to set or reset the cookie methods, and how to access them and how to remove them.

JSP 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 (although JavaScript can be set directly in a browser cookie) in the HTTP header information. JSP, set a cookie header to send the following information 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=w3big; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=w3big.com
Connection: close
Content-Type: text/html

As you can see, Set-Cookie header contains a key-value pair, a GMT (Greenwich Mean) time, a path, a domain name. Key-value pair is encoded as a URL. Validity of the field is a command that tells the browser after what time you can remove this cookie.

If your browser is configured to store cookie, then it will save the information until they expire. If the user visits any page match the cookie path and domain name, then the browser will re-send the cookie back to the server. Browser-side header looks 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

JSP scripts to access the cookie by request object getCookies () method, which returns an array of Cookie objects.


Servlet Cookie Methods

The following table lists the Cookie objects commonly used methods:

No. Method & description
1 public void setDomain (String pattern)

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

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

Setting cookie expiration, in seconds, the default is valid for the current session of the survival time
4 public int getMaxAge ()

Get cookie expiration, in seconds, the default is -1, indicating that the cookie will live up to the browser is closed
5 public String getName ()

Returns the name of the cookie, the name can not be changed after it is created
6 public void setValue (String newValue)

Set the value of the cookie
7 public String getValue ()

Gets the value of the cookie
8 public void setPath (String uri)

Setting the cookie path, the default is the current URL for all pages directory, and all subdirectories under the
9 public String getPath ()

Get cookie path
10 public void setSecure (boolean flag)

To indicate whether the cookie encrypted transmission
11 public void setComment (String purpose)

Setting comment to describe the purpose of the cookie. When the browser cookie presented to the user, comments will be very useful
12 public String getComment ()

Returns the comment describing the purpose of the cookie, or null if there is no

Cookie settings using JSP

Use JSP set cookie consists of three steps:

(1) Create a Cookie object: calling the constructor Cookie using a cookie name and value as parameters, they are strings.

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

Be sure to keep in mind that the names and values ​​can not contain spaces or the following characters:

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

(2) setting is valid: Call setMaxAge () function indicates how long the cookie is valid within (in seconds). The following will set valid for 24 hours.

cookie.setMaxAge(60*60*24); 

(3) sends the cookie to the HTTP response headers: Call response.addCookie () function to respond to the HTTP header to add cookie.

response.addCookie(cookie);

Examples Demo

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 via GET method to submit data to the client main.jsp file and set the cookie:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本教程(w3big.com)</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 into test.htm file.

Place the file in the current directory under WebContent jsp project (with main.jsp the same directory).

By visiting http: // localhost: 8080 / testjsp / test.html main.jsp submit the form data to a file, Gif demo shown below:

Try typing "site name" and "URL", then click the submit button, it will display the "site name" and "URL" in your screen, and set the "site name" and "URL" two cookie.


Use JSP to read Cookie

Want to read the cookie, you will need to call request.getCookies () method to get an array of javax.servlet.http.Cookie object, and then traverse the array using the method getName () and getValue () method to get each cookie the name and value.

Let's read the last example of the cookie, the following is 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 the browser access, output is:


Use JSP Delete Cookie

Remove cookie is very simple. If you want to delete a cookie, to follow the steps below to do on the line:

  • Being an existing cookie is then stored in a Cookie object.
  • The cookie will be set to 0.
  • This cookie will be added back into the response header.

Examples Demo

The following procedure deletes a cookie named "name" when you are the second run cookie.jsp, name will be 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>

Accessed through a browser, the output is:

Another visit http: // localhost: 8080 / testjsp / cookie.jsp, will get the following results:

You can see the name width = "70%" "name" of the cookie was gone.

You can also manually delete the cookie in your browser. IE browser by clicking on the Tools menu, then select Internet Options, click Delete Cookies, you can delete all the cookie.