Cookies are text files stored on the client computer that retain various tracking information. Java Servlets clearly support HTTP Cookies.
Identifying returning users involves three steps:
* The server script sends a set of cookies to the browser. For example: name, age, or identification number.
* The browser stores this information on the local computer for future use.
* When the browser sends any request to the web server next time, it sends these cookie information to the server, which uses this information 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 of Chinese characters, as follows:
>
> String str = java.net.URLEncoder.encode("Chinese", "UTF-8"); //Encoding
> String str = java.net.URLDecoder.decode("Encoded String", "UTF-8"); // Decoding
Cookies are usually set in the HTTP header (although JavaScript can also set a cookie directly in the browser). The Servlet that sets the cookie will send the following header information:
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=example.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 an instruction 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 expiration date. If the user's browser points to any page that matches the cookie's path and domain, it will resend the cookie to the server. The browser's header information 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 access the cookie through the request method _request.getCookies()_, which returns an array of _Cookie_ objects.
Here is a list of useful methods available when 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, example.com. |
| 2 | **public String getDomain()** This method gets the domain to which the cookie applies, for example, example.com. |
| 3 | **public void setMaxAge(int expiry)** This method sets the time (in seconds) for which a cookie should remain valid. If not set, the cookie will only be valid for the current session. |
| 4 | **public int getMaxAge()** This method returns the maximum age (in seconds) of the cookie. By default, -1 indicates 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 value indicating whether the cookie should only be sent over encrypted (i.e., SSL) connections. |
| 11 | **public void setComment(String purpose)** Sets the comment for the cookie. This comment is useful when the browser presents the cookie to the user. |
| 12 | **public String getComment()** Gets the comment for the cookie, or null if the cookie has no comment. |
Setting a cookie via a Servlet involves three steps:
**(1) Creating a Cookie object:** You can call the Cookie constructor with the cookie name and 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) Setting the maximum age:** You can use the setMaxAge method to specify how long (in seconds) the cookie should remain valid. The following will set a cookie with a maximum age of 24 hours.
cookie.setMaxAge(60*60*24);
**(3) Sending the Cookie to the HTTP response header:** You can use **response.addCookie** to add the cookie to the HTTP response header, as shown below:
response.addCookie(cookie);
## Example
Let's modify our (#) to set cookies for the first name and last name.
```java
package com.tutorial.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 HelloForm
*/
@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)
*/
protected 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")); // Encode Chinese characters
Cookie url = new Cookie("url", request.getParameter("url"));
// Set expiration date for both cookies to 24 hours
name.setMaxAge(60*60*24);
url.setMaxAge(60*60*24);
// Add both cookies to 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 = "Setting Cookies Example";
String docType = "n";
out.println(docType +
"n" +
"
" + title + "n" +
"n" +
"
" + title + "
n" +
"
n" +
" - Site Name:οΌ" + request.getParameter("name") + "n
" +
" - Site 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 above Servlet **HelloForm** and create appropriate entries in the web.xml file:
```xml
HelloForm
com.tutorial.test.HelloForm
HelloForm
/TomcatTest/HelloForm
Finally, try the following HTML page to invoke the Servlet.
(example.com)
Site Name οΌ
Site URLοΌ
Save the above HTML content 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 above paths need to be modified according to your project's actual path.
To read cookies, you need to create an array of _javax.servlet.http.Cookie_ objects by calling the **getCookies( )** method of _HttpServletRequest_. 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.
```java
package com.tutorial.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)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of cookies associated with 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 Names and Values
");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies;
if ((cookie.getName()).compareTo("name") == 0) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookieοΌ" + cookie.getName() + "
");
}
out.print("NameοΌ" + cookie.getName() + "οΌ");
out.print("ValueοΌ" + URLDecoder.decode(cookie.getValue(), "utf-8") + "
");
}
} else {
out.println("");
}
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 above Servlet **ReadCookies** and create appropriate entries in the web.xml file. Try running _http://localhost:8080/TomcatTest/ReadCookies_, and the following result will be displayed:
!(#)
Deleting a cookie is very simple. If you want to delete a cookie, you just need to follow these three steps:
* Read an existing cookie and store it in a Cookie object.
* Use the **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". When you run the ReadCookies Servlet next time, it will return url as null.
```java
package com.tutorial.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)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";
String docType = "n";
out.println(docType +
"n" +
"
" + title + "n" +
"n" );
if (cookies != null) {
out.println("
Cookie Names and Values
");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies;
if ((cookie.getName()).compareTo("url") == 0) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookieοΌ" + cookie.getName() + "
");
}
out.print("NameοΌ" + cookie.getName() + "οΌ");
out.print("ValueοΌ" + cookie.getValue() + "
");
}
} else {
out.println("");
}
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 above Servlet **DeleteCookies** and create appropriate entries in the web.xml file. Now run _http://localhost:8080/TomcatTest/DeleteCookies_, and the following result will be displayed:
!(#)