Servlet Cookie Handling
A Cookie is a text file stored on the client's computer that retains various tracking information. Java Servlets obviously support HTTP Cookies.
Identifying a returning user involves three steps:
- The server script sends a set of Cookies to the browser, for example: name, age, or 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, it sends this Cookie information to the server, which uses it to identify the user.
This chapter will explain how to set or reset Cookies, how to access them, and how to delete them.
Servlet Cookie handling requires encoding and decoding Chinese, 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 the HTTP header (although JavaScript can also set a Cookie directly in the browser). A Servlet that sets a Cookie sends 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=runoob.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name-value pair, a GMT date, a path, and a domain. The name and value are URL-encoded. The expires field is a directive that tells the browser to "forget" the Cookie after the given time and date.
If the browser is configured to store Cookies, it will retain this information until the expiry date. If the user's browser points to any page matching the Cookie's path and domain, it will resend the Cookie to the server. The browser's header 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
The Servlet can then use the request method request.getCookies() to access Cookies; this method returns an array of Cookie objects.
Servlet Cookie Methods
The following is a list of useful methods available for manipulating Cookies in a Servlet.
| No. | Method & Description |
|---|---|
| 1 | public void setDomain(String pattern) |
| This method sets the domain to which the cookie applies, for example, runoob.com. | |
| 2 | public String getDomain() |
| This method gets the domain to which the cookie applies, for example, runoob.com. | |
| 3 | public void setMaxAge(int expiry) |
| This method sets the time until the cookie expires (in seconds). If not set this way, the cookie will only last for the current session. | |
| 4 | public int getMaxAge() |
| This method returns the maximum lifetime of the cookie (in seconds); by default, -1 means the cookie will persist until the browser is closed. | |
| 5 | public String getName() |
| This method returns the name of the cookie. The name cannot be changed after creation. | |
| 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 which the cookie applies. If you do not specify a path, all URLs under the same directory as the current page (including subdirectories) will return the cookie. | |
| 9 | public String getPath() |
| This method gets the path to which the cookie applies. | |
| 10 | public void setSecure(boolean flag) |
| This method sets a boolean indicating whether the cookie should be sent only over encrypted (i.e., SSL) connections. | |
| 11 | public void setComment(String purpose) |
| Sets the cookie's comment. This comment is useful when the browser presents the cookie to the user. | |
| 12 | public String getComment() |
| Gets the cookie's comment, or null if the cookie has no comment. |
Setting Cookies Through a Servlet
Setting Cookies through a Servlet involves three steps:
**(1) Create a Cookie object:** You can call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Remember that neither the name nor the value should contain spaces or any of the following characters:
[ ] ( ) = , " / ? @ : ;
**(2) Set the maximum lifetime:** You can use the setMaxAge method to specify how long a cookie can remain valid (in seconds). The following will set a cookie with a maximum validity of 24 hours.
cookie.setMaxAge(60*60*24);
**(3) Send the Cookie in the HTTP response header:** You can use response.addCookie to add a Cookie to the HTTP response header, as shown below:
response.addCookie(cookie);
Example
Let's modify our form data exampleto set cookies for the first name and last name.
package com.runoob.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
{
// Create cookies for first name and last name
Cookie name = new Cookie("name",
URLEncoder.encode(request.getParameter("name"), "UTF-8")); // 中文转码
Cookie url = new Cookie("url",
request.getParameter("url"));
// Set expiration date for two cookies to 24 hours later
name.setMaxAge(60*60*24);
url.setMaxAge(60*60*24);
// Add two cookies in the response header
response.addCookie( name );
response.addCookie( url );
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Set Cookie Example";
String docType = "\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"\n" +
" - 站点名::"
+ request.getParameter("name") + "\n
" +
" - 站点 URL::"
+ request.getParameter("url") + "\n
" +
"
\n" +
"");
}
/**
* @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 Servlet above HelloFormand create the appropriate entries in the web.xml file:
HelloForm
com.runoob.test.HelloForm
HelloForm
/TomcatTest/HelloForm
Finally, try the following HTML page to invoke the Servlet.
Runoob Tutorial(runoob.com)
Save the HTML content above to the file /TomcatTest/test.html.
Next we visit http://localhost:8080/TomcatTest/test.html, and the GIF demonstration is as follows:

Note:Some of the paths above need to be modified according to the actual paths of your project.
Reading Cookies through a Servlet
To read a Cookie, you need to call the HttpServletRequest 's getCookies( ) method to create an array of javax.servlet.http.Cookie objects. Then loop through the array and use the getName() and getValue() methods to access each cookie and its associated value.
Example
Let's read the Cookies set in the example above
package com.runoob.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;
// Get an array of cookies related to this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Delete Cookie Example";
String docType = "\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" );
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("值:" + URLDecoder.decode(cookie.getValue(), "utf-8") +"
");
}
}else{
out.println(
"No Cookie founds
");
}
out.println("");
out.println("");
}
/**
* @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 Servlet above ReadCookiesand create the appropriate entries in the web.xml file. Try running http://localhost:8080/TomcatTest/ReadCookiesand the following result will be displayed:

Deleting Cookies through a Servlet
Deleting a Cookie 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 a Cookie object.
- Use setMaxAge() method to set the cookie's age to zero, to delete the existing cookie.
- Add this cookie to the response header.
Example
The following example will delete the existing cookie named "url"; the next time you run the ReadCookies Servlet, it will return url as null.
package com.runoob.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;
// Get an array of cookies related to this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Delete Cookie Example";
String docType = "\n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" );
if( cookies != null ){
out.println("Cookie 名称和值
");
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( ) + "
");
}
out.print("名称:" + cookie.getName( ) + ",");
out.print("值:" + cookie.getValue( )+"
");
}
}else{
out.println(
"No Cookie founds
");
}
out.println("");
out.println("");
}
/**
* @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 Servlet above DeleteCookiesand create the appropriate entries in the web.xml file. Now run http://localhost:8080/TomcatTest/DeleteCookiesand the following result will be displayed:
