JSP Cookie Handling
Cookies are text files stored on the client machine; they hold a large amount of tracking information. Built on Servlet technology, JSP can obviously provide support for HTTP cookies.
There are usually three steps to identify returning visitors:
- The server script sends a series of cookies to the browser, such as name, age, ID number, and so on.
- The browser stores this information on the local machine for later use.
- The next time the browser sends any request to the server, it sends this cookie information to the server as well, and the server uses the information to identify the user or do other things.
This chapter will teach you how to set or reset cookies, as well as how to access and delete them.
JSP Cookie handling requires encoding and decoding of Chinese text, as follows:
String str = java.net.URLEncoder.encode("Chinese", "UTF-8"); // encode String str = java.net.URLDecoder.decode("encoded string", "UTF-8"); // decode
Anatomy of a Cookie
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 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=runoob; expires=Friday, 04-Feb-17 22:03:38 GMT;
path=/; domain=runoob.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a key-value pair, a GMT (Greenwich Mean Time) time, a path, and a domain. The key-value pair is URL-encoded. The expires field is a directive that tells the browser when it can clear this cookie.
If the browser is configured to store cookies, it will keep this information until it expires. If the user visits any page that matches the path and domain in the cookie, the browser will send the cookie back to the server. The header on the browser side 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 access these cookies through the getCookies() method of the request object, which returns an array of Cookie objects.
Servlet Cookie Methods
The following table lists the commonly used methods in the Cookie object:
| No. | Method** & **Description |
|---|---|
| 1 | public void setDomain(String pattern) Sets the domain of the cookie, for example, runoob.com |
| 2 | public String getDomain() Gets the domain of the cookie, for example, runoob.com |
| 3 | public void setMaxAge(int expiry) Sets the cookie's validity period in seconds; by default it is the lifetime of the current session |
| 4 | public int getMaxAge() Gets the cookie's validity period in seconds; the default is -1, indicating the cookie lives until the browser is closed |
| 5 | public String getName() Returns the name of the cookie; once created, the name cannot be changed |
| 6 | public void setValue(String newValue) Sets the value of the cookie |
| 7 | public String getValue() Gets the value of the cookie |
| 8 | public void setPath(String uri) Sets the path of the cookie; by default it is all URLs under the current page's directory, as well as all subdirectories under this directory |
| 9 | public String getPath() Gets the path of the cookie |
| 10 | public void setSecure(boolean flag) Indicates whether the cookie should be transmitted with encryption |
| 11 | public void setComment(String purpose) Sets a comment describing the purpose of the cookie. The comment is very useful when the browser presents the cookie to the user. |
| 12 | public String getComment() Returns the comment describing the purpose of the cookie, or null if there is none |
Setting Cookies Using JSP
Setting cookies using JSP involves three steps:
** (1) Create a cookie object: ** Call the cookie constructor with a cookie name and value as arguments, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind that neither the name nor the value may contain spaces or the following characters:
[ ] ( ) = , " / ? @ : ;
** (2) Set the validity period:** Call the setMaxAge() function to indicate how long (in seconds) the cookie is valid. The following sets the validity period to 24 hours.
cookie.setMaxAge(60*60*24);
** (3) Send the cookie in the HTTP response header:** Call the response.addCookie() function to add the cookie to the 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 );
%>
设置 Cookie
设置 Cookie
网站名:
<%= request.getParameter("name")%>
网址:
<%= request.getParameter("url")%>
The following is a simple HTML form that submits client data to the main.jsp file via the GET method and sets cookies:
Runoob Tutorial(runoob.com)
Save the above HTML code to a file named test.htm.
Place this file in the WebContent directory of the current jsp project (the same directory as main.jsp).
By accessing http://localhost:8080/testjsp/test.html to submit form data to the main.jsp file, the demonstration GIF is as follows:

Try entering "Site Name" and "URL", then click the submit button; it will display "Site Name" and "URL" on your screen and set two cookies for "Site Name" and "URL".
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 traverse the array and use the getName() and getValue() methods to get the name and value of each cookie.
Let's read the cookies from the previous example. The code for the cookie.jsp file is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
获取 Cookie
<%
Cookie cookie = null;
Cookie[] cookies = null;
// 获取 cookies 的数据,是一个数组
cookies = request.getCookies();
if( cookies != null ){
out.println(" 查找 Cookie 名与值
");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("参数名 : " + cookie.getName());
out.print("
");
out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +"
");
out.print("------------------------------------
");
}
}else{
out.println("
No Cookie found
");
}
%>
After accessing with a browser, the output is:

Deleting Cookies Using JSP
Deleting a cookie is very simple. If you want to delete a cookie, just follow the steps below:
- Obtain an existing cookie and store it in a Cookie object.
- Set the cookie's validity period to 0.
- Add this cookie back into the response header.
Example Demonstration
The following program deletes a cookie named "name"; when you run cookie.jsp a second time, name will be null.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
获取 Cookie
<%
Cookie cookie = null;
Cookie[] cookies = null;
// 获取当前域名下的cookies,是一个数组
cookies = request.getCookies();
if( cookies != null ){
out.println(" 查找 Cookie 名与值
");
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( ) + "
");
}
out.print("参数名 : " + cookie.getName());
out.print("
");
out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +"
");
out.print("------------------------------------
");
}
}else{
out.println("没有发现 Cookie
");
}
%>
Accessing via a browser, the output is:

Visit again http://localhost:8080/testjsp/cookie.jspthe following result will be obtained:

You can see that the cookie named "name" is gone.
You can also delete cookies manually in the browser. In IE, click the Tools menu item, then select Internet Options, and click Delete Cookies to delete all cookies.