JSP Cookie Handling
Cookies are text files stored on the client machine that hold a large amount of tracking information. On top of Servlet technology, JSP can clearly provide 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 needs.
The next time the browser sends any request to the server, it will also send this cookie information to the server, which then uses this information to identify the user or do other things.
This section 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 in Chinese, as follows:
String str = java.net.URLEncoder.encode("中文", "UTF-8"); // Encoding
String str = java.net.URLDecoder.decode("Encoded String", "UTF-8"); // Decoding
Cookie Anatomy
Cookies are usually 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.0b3
Set-Cookie: name=tutorialpro; expires=Friday, 04-Feb-17 22:03:38 GMT;
path=/; domain=tutorialpro.org
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header includes a key-value pair, a GMT (Greenwich Mean Time), a path, and a domain. The key-value pair is URL-encoded. The expiration field is an instruction telling the browser when to clear the 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 resend the cookie to the server. The browser's 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 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 commonly used methods in the Cookie object:
Number | Method & Description |
---|---|
1 | public void setDomain(String pattern) Sets the domain of the cookie, e.g., tutorialpro.org |
2 | public String getDomain() Gets the domain of the cookie, e.g., tutorialpro.org |
3 | public void setMaxAge(int expiry) Sets the cookie's expiration time in seconds; the default expiration is the duration of the current session |
4 | public int getMaxAge() Gets the cookie's expiration time in seconds; default is -1, indicating the cookie will live until the browser is closed |
5 | public String getName() Returns the name of the cookie, which cannot be changed after creation |
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; default is all URLs under the current page directory and all subdirectories under this directory |
9 | public String getPath() Gets the path of the cookie |
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 purpose of the cookie. The comment is 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 none exists |
Setting Cookies with JSP
Setting cookies with JSP involves three steps:
(1) Create a cookie object: Call the cookie constructor with a cookie name and value as parameters, both of which are strings.
Cookie cookie = new Cookie("key","value");
It is important to 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:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<%
// Encoding to resolve Chinese乱码
String str = URLEncoder.encode(request.getParameter("name"),"utf-8");
// Setting name and url cookies
Cookie name = new Cookie("name",
str);
Cookie url = new Cookie("url",
request.getParameter("url"));
// Setting cookie expiration time to 24 hours
name.setMaxAge(60*60*24);
url.setMaxAge(60*60*24);
// Adding cookie to response header
response.addCookie(name);
response.addCookie(url);
%>
<html>
<head>
<title>Setting Cookie</title>
</head>
<body>
<h1>Setting Cookie</h1>
<ul>
<li><p><b>Site Name:</b>
<%= request.getParameter("name")%>
</p></li>
<li><p><b>URL:</b>
<%= request.getParameter("url")%>
</p></li>
</ul>
</body>
</html>
The following is a simple HTML form that submits client data to the main.jsp file using the GET method and sets a cookie:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
</head>
<body>
<form action="main.jsp" method=GET>
Site Name: <input type="text" name="name">
<br />
URL: <input type="text" name="url" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Save the above HTML code in a file named test.htm.
Place this file in the WebContent directory of your current JSP project (same directory as main.jsp).
Access http://localhost:8080/testjsp/test.html to submit form data to the main.jsp file, as shown in the following GIF: 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 with JSP
To read cookies, 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 retrieve the name and value of each cookie.
#
Let's read the cookies from the previous example. Below is the code for the cookie.jsp
file:
<%@ 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>Get Cookies</title>
</head>
<body>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get the cookies data, which is an array
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Finding Cookie Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Parameter Name : " + cookie.getName());
out.print("<br>");
out.print("Parameter Value: " + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br>");
out.print("------------------------------------<br>");
}
}else{
out.println("<h2>No Cookies Found</h2>");
}
%>
</body>
</html>
After accessing the browser, the output is:
Deleting Cookies with JSP
Deleting a cookie is very simple. If you want to delete a cookie, follow these steps:
Get an existing cookie and store it in a Cookie object.
Set the cookie's expiration to 0.
Re-add this cookie to the response header.
Example Demonstration
The following program deletes a cookie named "name". When you run cookie.jsp
for the second time, "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>Get Cookies</title>
</head>
<body>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get the cookies for the current domain, which is an array
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Finding Cookie Name and Value</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("Deleting Cookie: " +
cookie.getName() + "<br/>");
}
out.print("Parameter Name: " + cookie.getName());
out.print("<br>");
out.print("Parameter Value: " + URLDecoder.decode(cookie.getValue(), "utf-8") + " <br>");
out.print("------------------------------------<br>");
}
} else {
out.println("<h2>No Cookies Found</h2>");
}
%>
</body>
</html>
When accessed through a browser, the output is:
When you visit http://localhost:8080/testjsp/cookie.jsp again, you will get the following result:
You can see that the cookie named "name" is no longer present.
You can also manually delete cookies in your browser. In Internet Explorer, click on the Tools menu, select Internet Options, click Delete Cookies, and this will remove all cookies. ```