Servlet Cookies Handling
Cookies are text files that are stored on the client's computer and retain various tracking information. Java Servlets apparently 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, etc.
The browser stores this information locally on your computer for future use.
The next time the browser sends any request to the web server, the browser will send these Cookies information to the server, and the server will use this information to identify the user.
This chapter will teach you how to set or reset Cookies, how to access them, and how to delete them.
Cookie Anatomy
Cookies are usually set in HTTP headers (although JavaScript can also set a cookie directly on 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=w3cschool.cc 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. Names and values will be URL encoded. The expires field is an instruction that tells the browser to "forget" the cookie after a given time and date.
If your 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 resends the cookie to the server. The header information of the browser may look like the following:
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
Servlet can access Cookie through the request method request.getCookies(), which will return a Cookie object array.
Servlet Cookies Methods
The following is a list of useful methods that can be used when manipulating Cookies in Servlets.
Serial number | Method & Description |
---|---|
1 | public void setDomain(String pattern ) This method sets the domain to which the cookie applies, such as w3cschool.cc. |
2 | public String getDomain() This method gets the domain to which the cookie applies, such as w3cschool.cc. |
3 | public void setMaxAge(int expiry) This method sets the cookie expiration time (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 Below, -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 for the cookie. If you do not specify a path, all URLs in the same directory as the current page (including subdirectories) will return cookies. |
9 | public String getPath() This method gets the path applicable to the cookie. |
10 | public void setSecure(boolean flag) This method sets a Boolean value indicating whether the cookie should only be encrypted ( i.e. SSL) connection. |
11 | public void setComment(String purpose) This method specifies a comment describing the purpose of the cookie. This annotation is useful when the browser presents the cookie to the user. |
12 | public String getComment() This method returns a comment describing the purpose of the cookie. If the cookie has no comment, it returns null. . |
Set Cookies through Servlet
Setting Cookies through Servlet includes three steps:
(1) Create a Cookie object: You can call with Cookie constructor with cookie name and cookie value, both cookie name and cookie value are strings.
Cookie cookie = new Cookie("key","value");
Please remember that neither name nor 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, in seconds, the cookie remains valid. The following will set a cookie with a maximum validity period of 24 hours.
cookie.setMaxAge(60*60*24);
(3) Send Cookie to HTTP response header: You can use response.addCookie to add Cookies in the HTTP response header, as shown below:
response.addCookie(cookie);
Example
Let's modify our form data instance to set cookies for first name and last name.
// 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // 扩展 HttpServlet 类 public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 为名字和姓氏创建 Cookies Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // 为两个 Cookies 设置过期日期为 24 小时后 firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // 在响应头中添加两个 Cookies response.addCookie( firstName ); response.addCookie( lastName ); // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "设置 Cookies 实例"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>名字</b>:" + request.getParameter("first_name") + "\n</li>" + " <li><b>姓氏</b>:" + request.getParameter("last_name") + "\n</li>" + "</ul>\n" + "</body></html>"); } }
Compile the above Servlet HelloForm and create appropriate entries in the web.xml file and finally try the following HTML page to call the Servlet.
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <form action="HelloForm" method="GET"> 名字:<input type="text" name="first_name"> <br /> 姓氏:<input type="text" name="last_name" /> <input type="submit" value="提交" /> </form> </body> </html>
Save the above HTML content to the file hello.htm and place it in the <Tomcat-installation-directory>/webapps/ROOT directory. When you visit http://localhost:8080/Hello.htm, the actual output of the above form looks like this:
Try entering first name and last name, then Click the "Submit" button, the first name and last name will be displayed on the screen, and the two Cookies firstName and lastName will be set. When you press the Submit button next time, these two Cookies will be transferred back to the server.
The next section explains how to access these cookies in web applications.
Reading Cookies through Servlet
To read Cookies, you need to create a javax by calling the getCookies( ) method of HttpServletRequest .servlet.http.Cookie Array of objects. Then it loops through the array and accesses each cookie and associated value using the getName() and getValue() methods.
Example
Let us read the Cookies set in the above example
// 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // 扩展 HttpServlet 类 public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // 获取与该域相关的 Cookies 的数组 cookies = request.getCookies(); // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Reading Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2>查找 Cookies 名称和值</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("名称:" + cookie.getName( ) + ","); out.print("值:" + cookie.getValue( )+" <br/>"); } }else{ out.println("<h2>未找到 Cookies</h2>"); } out.println("</body>"); out.println("</html>"); } }
Compile the above Servlet ReadCookies, and in the web.xml file Create appropriate entries. If you have set the first_name cookie to "John" and the last_name cookie to "Player", try to run http://localhost:8080/ReadCookies, the following results will be displayed:
Find Cookies name and valueName: first_name, value: JohnName: last_name, value: Player |
Deleting Cookies through Servlet
Deleting Cookies is very simple. If you want to delete a cookie, then you just need to follow these three steps:
Read an existing cookie and store it in the Cookie object.
Use the setMaxAge() method to set the cookie's age to zero to delete existing cookies.
Add this cookie to the response header.
Example
The following example will delete the existing cookie named "first_name". When you run the ReadCookies Servlet next time, it will return first_name as NULL value.
// 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // 扩展 HttpServlet 类 public class DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // 获取与该域相关的 Cookies 的数组 cookies = request.getCookies(); // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Delete Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2>Cookies 名称和值</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("已删除的 cookie:" + cookie.getName( ) + "<br/>"); } out.print("名称:" + cookie.getName( ) + ","); out.print("值:" + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2 class="tutheader">No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } }
Compile the above Servlet DeleteCookies and create the appropriate entries in the web.xml file. Now run http://localhost:8080/DeleteCookies, the following results will be displayed:
Cookies name and valueDeleted cookie: first_nameName: first_name, value: John Name: last_name, value: Player |
Now try to run http://localhost :8080/ReadCookies, it will display only one cookie as follows:
Find Cookies name and valueName: last_name, value :Player |
#You can manually delete cookies in Internet Explorer. On the "Tools" menu, select "Internet Options". If you want to delete all cookies, click "Delete Cookies".