Cookies are text files stored on the client machine, holding a large amount of tracking information. Building on Servlet technology, JSP obviously provides support for HTTP cookies.
Typically, there are three steps to identify returning visitors:
* The server script sends a series of cookies to the browser. For example, name, age, ID number, etc.
* The browser stores this information locally for future use.
* The next time the browser sends any request to the server, it also sends this cookie information to the server, and then the server uses this information to identify the user or do something else.
This chapter will teach you how to set or reset cookies, how to access them, and how to delete them.
> JSP Cookie handling requires encoding and decoding for 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
* * *
## Cookie Anatomy
Cookies are typically set in the HTTP header (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.0b3Set-Cookie: name=tutorial; expires=Friday, 04-Feb-17 22:03:38 GMT; path=/; domain=example.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 encoded as a URL. The expires field is an instruction that tells the browser when it can clear this cookie.
If the browser is configured to store cookies, it will save this information until it expires. If any page the user visits matches the path and domain in the cookie, the browser will send this cookie back to the server. The header on the browser side looks like this:
GET / HTTP/1.0Connection: Keep-AliveUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)Host: zink.demon.co.uk:1126Accept: 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 in the request object, which returns an array of Cookie objects.
* * *
## Servlet Cookie Methods
The following table lists the common methods in the Cookie object:
| **No.** | **Method & Description** |
| --- | --- |
| 1 | **public void setDomain(String pattern)** Sets the domain of the cookie, e.g., example.com |
| 2 | **public String getDomain()** Gets the domain of the cookie, e.g., example.com |
| 3 | **public void setMaxAge(int expiry)** Sets the cookie's maximum age in seconds. The default is the lifetime of the current session. |
| 4 | **public int getMaxAge()** Gets the cookie's maximum age in seconds. The default is -1, indicating the cookie will last until the browser closes. |
| 5 | **public String getName()** Returns the cookie's name. The name cannot be changed after creation. |
| 6 | **public void setValue(String newValue)** Sets the cookie's value. |
| 7 | **public String getValue()** Gets the cookie's value. |
| 8 | **public void setPath(String uri)** Sets the cookie's path. The default is all URLs under the current page directory and all subdirectories of this directory. |
| 9 | **public String getPath()** Gets the cookie's path. |
| 10 | **public void setSecure(boolean flag)** Specifies whether the cookie should be transmitted securely. |
| 11 | **public void setComment(String purpose)** Sets a comment describing the cookie's purpose. This comment becomes very useful when the browser displays the cookie to the user. |
| 12 | **public String getComment()** Returns the comment describing the cookie's purpose, or null if there is none. |
* * *
## Setting Cookies with JSP
Setting cookies with 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 expiration time:** Call the setMaxAge() function to specify how long (in seconds) the cookie is valid. The following operation sets the expiration time to 24 hours.
cookie.setMaxAge(60*60*24);
**(3) Send the cookie to the HTTP response header:** Call the response.addCookie() function to add the cookie to the HTTP response header.
response.addCookie(cookie);
* * *
### Example Demonstration
The code for the main.jsp file is as follows:
Set CookieSet Cookie
Here is a simple HTML form that submits client data to the main.jsp file via the GET method and sets cookies:
Site Name:
URL:
Save the above HTML code to a test.htm file.
Place this file in the WebContent directory of the current JSP project (in 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 shown below:
!(#)
Try entering a "Site Name" and "URL", then click the submit button. It will display the "Site Name" and "URL" on your screen and set two cookies for "Site Name" and "URL".
* * *
## Reading Cookies with JSP
To read a cookie, you need to call the request.getCookies() method to get an array of javax.servlet.http.Cookie objects, then iterate through this array, using the getName() and getValue() methods to get the name and value of each cookie.
Let's read the cookies from the previous example. The following is the code for the cookie.jsp file:
Get Cookie<% Cookie cookie = null; Cookie[] cookies = null; // Get cookie data, which is an array cookies = request.getCookies(); if( cookies != null ){ out.println("
Find Cookie Name and Value
"); for (int i = 0; i < cookies.length; i++){ cookie = cookies; out.print("Parameter Name : " + cookie.getName()); out.print("
"); out.print("Parameter Value: " + URLDecoder.decode(cookie.getValue(), "utf-8") +"
"); out.print("------------------------------------
"); } }else{ out.println("
No Cookie Found
"); } %>
After the browser accesses it, the output result is:
!(#)
* * *
## Deleting Cookies with JSP
Deleting cookies is very simple. If you want to delete a cookie, follow the steps given below:
* Get an existing cookie and store it in a Cookie object.
* Set the cookie's maximum age 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 a second time, the name will be null.
Get Cookie<% Cookie cookie = null; Cookie[] cookies = null; // Get cookies for the current domain, which is an array cookies = request.getCookies(); if( cookies != null ){ out.println("
Find Cookie Name and Value
"); for (int i = 0; i < cookies.length; i++){ cookie = cookies; if((cookie.getName( )).compareTo("name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Delete Cookie: " + cookie.getName( ) + "
"); } out.print("Parameter Name : " + cookie.getName()); out.print("
"); out.print("Parameter Value: " + URLDecoder.decode(cookie.getValue(), "utf-8") +"
"); out.print("------------------------------------
"); } }else{ out.println("
No Cookie Found
"); } %>
Accessing via the browser, the output result is:
!(#)
Accessing **http://localhost:8080/testjsp/cookie.jsp** again will yield the following result:
!(#)
You can see that the cookie named "name" is gone.
You can also manually delete cookies in the browser. In Internet Explorer, you can delete all cookies by clicking the Tools menu item, then selecting Internet Options, and clicking Delete Cookies.