Servlet Cookies 处理
Cookies 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息。Java Servlet 显然支持 HTTP Cookies。
识别返回用户包括三个步骤:
- 服务器脚本向浏览器发送一组 Cookies。例如:姓名、年龄或识别号码等。
- 浏览器将这些信息存储在本地计算机上,以备将来使用。
- 当下一次浏览器向 Web 服务器发送任何请求时,浏览器会把这些 Cookies 信息发送到服务器,服务器将使用这些信息来识别用户。
本章将向您讲解如何设置或重置 Cookies,如何访问它们,以及如何将它们删除。
Cookie 剖析
Cookies 通常设置在 HTTP 头信息中(虽然 JavaScript 也可以直接在浏览器上设置一个 Cookie)。设置 Cookie 的 Servlet 会发送如下的头信息:
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/htm
正如您所看到的,Set-Cookie 头包含了一个名称值对、一个 GMT 日期、一个路径和一个域。名称和值会被 URL 编码。expires 字段是一个指令,告诉浏览器在给定的时间和日期之后"忘记"该 Cookie。
如果浏览器被配置为存储 Cookies,它将会保留此信息直到到期日期。如果用户的浏览器指向任何匹配该 Cookie 的路径和域的页面,它会重新发送 Cookie 到服务器。浏览器的头信息可能如下所示:
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 Cookies 方法
以下是在 Servlet 中操作 Cookies 时可使用的有用的方法列表。
序号 | 方法 & 描述 |
---|---|
1 | public void setDomain(String pattern) 该方法设置 cookie 适用的域,例如 w3cschool.cc。 |
2 | public String getDomain() 该方法获取 cookie 适用的域,例如 w3cschool.cc。 |
3 | public void setMaxAge(int expiry) 该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中持续有效。 |
4 | public int getMaxAge() 该方法返回 cookie 的最大生存周期(以秒为单位),默认情况下,-1 表示 cookie 将持续下去,直到浏览器关闭。 |
5 | public String getName() 该方法返回 cookie 的名称。名称在创建后不能改变。 |
6 | public void setValue(String newValue) 该方法设置与 cookie 关联的值。 |
7 | public String getValue() 该方法获取与 cookie 关联的值。 |
8 | public void setPath(String uri) 该方法设置 cookie 适用的路径。如果您不指定路径,与当前页面相同目录下的(包括子目录下的)所有 URL 都会返回 cookie。 |
9 | public String getPath() 该方法获取 cookie 适用的路径。 |
10 | public void setSecure(boolean flag) 该方法设置布尔值,表示 cookie 是否应该只在加密的(即 SSL)连接上发送。 |
11 | public void setComment(String purpose) 该方法规定了描述 cookie 目的的注释。该注释在浏览器向用户呈现 cookie 时非常有用。 |
12 | public String getComment() 该方法返回了描述 cookie 目的的注释,如果 cookie 没有注释则返回 null。 |
通过 Servlet 设置 Cookies
通过 Servlet 设置 Cookies 包括三个步骤:
(1) 创建一个 Cookie 对象:您可以调用带有 cookie 名称和 cookie 值的 Cookie 构造函数,cookie 名称和 cookie 值都是字符串。
Cookie cookie = new Cookie("key","value");
请记住,无论是名字还是值,都不应该包含空格或以下任何字符:
[ ] ( ) = , " / ? @ : ;
(2) 设置最大生存周期:您可以使用 setMaxAge 方法来指定 cookie 能够保持有效的时间(以秒为单位)。下面将设置一个最长有效期为 24 小时的 cookie。
cookie.setMaxAge(60*60*24);
(3) 发送 Cookie 到 HTTP 响应头:您可以使用 response.addCookie 来添加 HTTP 响应头中的 Cookies,如下所示:
response.addCookie(cookie);
实例
让我们修改我们的 表单数据实例,为名字和姓氏设置 Cookies。

1 // 导入必需的 java 库 2 import java.io.*; 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 6 // 扩展 HttpServlet 类 7 public class HelloForm extends HttpServlet { 8 9 public void doGet(HttpServletRequest request, 10 HttpServletResponse response) 11 throws ServletException, IOException 12 { 13 // 为名字和姓氏创建 Cookies 14 Cookie firstName = new Cookie("first_name", 15 request.getParameter("first_name")); 16 Cookie lastName = new Cookie("last_name", 17 request.getParameter("last_name")); 18 19 // 为两个 Cookies 设置过期日期为 24 小时后 20 firstName.setMaxAge(60*60*24); 21 lastName.setMaxAge(60*60*24); 22 23 // 在响应头中添加两个 Cookies 24 response.addCookie( firstName ); 25 response.addCookie( lastName ); 26 27 // 设置响应内容类型 28 response.setContentType("text/html"); 29 30 PrintWriter out = response.getWriter(); 31 String title = "设置 Cookies 实例"; 32 String docType = 33 "<!doctype html public \"-//w3c//dtd html 4.0 " + 34 "transitional//en\">\n"; 35 out.println(docType + 36 "<html>\n" + 37 "<head><title>" + title + "</title></head>\n" + 38 "<body bgcolor=\"#f0f0f0\">\n" + 39 "<h1 align=\"center\">" + title + "</h1>\n" + 40 "<ul>\n" + 41 " <li><b>名字</b>:" 42 + request.getParameter("first_name") + "\n" + 43 " <li><b>姓氏</b>:" 44 + request.getParameter("last_name") + "\n" + 45 "</ul>\n" + 46 "</body></html>"); 47 } 48 }
编译上面的 Servlet HelloForm,并在 web.xml 文件中创建适当的条目,最后尝试下面的 HTML 页面来调用 Servlet。
<html> <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>
保存上面的 HTML 内容到文件 hello.htm 中,并把它放在 <Tomcat-installation-directory>/webapps/ROOT 目录中。当您访问 http://localhost:8080/Hello.htm 时,上面表单的实际输出如下所示:
尝试输入名字和姓氏,然后点击"提交"按钮,名字和姓氏将显示在屏幕上,同时会设置 firstName 和 lastName 这两个 Cookies,当下次您按下提交按钮时,会将这两个 Cookies 传回到服务器。
下一节会讲解如何在 Web 应用程序中访问这些 Cookies。
通过 Servlet 读取 Cookies
要读取 Cookies,您需要通过调用 HttpServletRequest 的 getCookies( ) 方法创建一个 javax.servlet.http.Cookie 对象的数组。然后循环遍历数组,并使用 getName() 和 getValue() 方法来访问每个 cookie 和关联的值。
实例
让我们读取上面的实例中设置的 Cookies。

1 // 导入必需的 java 库 2 import java.io.*; 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 6 // 扩展 HttpServlet 类 7 public class ReadCookies extends HttpServlet { 8 9 public void doGet(HttpServletRequest request, 10 HttpServletResponse response) 11 throws ServletException, IOException 12 { 13 Cookie cookie = null; 14 Cookie[] cookies = null; 15 // 获取与该域相关的 Cookies 的数组 16 cookies = request.getCookies(); 17 18 // 设置响应内容类型 19 response.setContentType("text/html"); 20 21 PrintWriter out = response.getWriter(); 22 String title = "Reading Cookies Example"; 23 String docType = 24 "<!doctype html public \"-//w3c//dtd html 4.0 " + 25 "transitional//en\">\n"; 26 out.println(docType + 27 "<html>\n" + 28 "<head><title>" + title + "</title></head>\n" + 29 "<body bgcolor=\"#f0f0f0\">\n" ); 30 if( cookies != null ){ 31 out.println("<h2>查找 Cookies 名称和值</h2>"); 32 for (int i = 0; i < cookies.length; i++){ 33 cookie = cookies[i]; 34 out.print("名称:" + cookie.getName( ) + ","); 35 out.print("值:" + cookie.getValue( )+" <br/>"); 36 } 37 }else{ 38 out.println( 39 "<h2 class="tutheader">未找到 Cookies</h2>"); 40 } 41 out.println("</body>"); 42 out.println("</html>"); 43 } 44 }
编译上面的 Servlet ReadCookies,并在 web.xml 文件中创建适当的条目。如果您已经设置了 first_name cookie 为 "John",last_name cookie 为 "Player" ,尝试运行 http://localhost:8080/ReadCookies,将显示如下结果:
通过 Servlet 删除 Cookies
删除 Cookies 是非常简单的。如果您想删除一个 cookie,那么您只需要按照以下三个步骤进行:
- 读取一个现有的 cookie,并把它存储在 Cookie 对象中。
- 使用 setMaxAge() 方法设置 cookie 的年龄为零,来删除现有的 cookie。
- 把这个 cookie 添加到响应头。
实例
下面的例子将删除现有的名为 "first_name" 的 cookie,当您下次运行 ReadCookies 的 Servlet 时,它会返回 first_name 为空值。

1 // 导入必需的 java 库 2 import java.io.*; 3 import javax.servlet.*; 4 import javax.servlet.http.*; 5 6 // 扩展 HttpServlet 类 7 public class DeleteCookies extends HttpServlet { 8 9 public void doGet(HttpServletRequest request, 10 HttpServletResponse response) 11 throws ServletException, IOException 12 { 13 Cookie cookie = null; 14 Cookie[] cookies = null; 15 // 获取与该域相关的 Cookies 的数组 16 cookies = request.getCookies(); 17 18 // 设置响应内容类型 19 response.setContentType("text/html"); 20 21 PrintWriter out = response.getWriter(); 22 String title = "Delete Cookies Example"; 23 String docType = 24 "<!doctype html public \"-//w3c//dtd html 4.0 " + 25 "transitional//en\">\n"; 26 out.println(docType + 27 "<html>\n" + 28 "<head><title>" + title + "</title></head>\n" + 29 "<body bgcolor=\"#f0f0f0\">\n" ); 30 if( cookies != null ){ 31 out.println("<h2>Cookies 名称和值</h2>"); 32 for (int i = 0; i < cookies.length; i++){ 33 cookie = cookies[i]; 34 if((cookie.getName( )).compareTo("first_name") == 0 ){ 35 cookie.setMaxAge(0); 36 response.addCookie(cookie); 37 out.print("已删除的 cookie:" + 38 cookie.getName( ) + "<br/>"); 39 } 40 out.print("名称:" + cookie.getName( ) + ","); 41 out.print("值:" + cookie.getValue( )+" <br/>"); 42 } 43 }else{ 44 out.println( 45 "<h2 class="tutheader">No cookies founds</h2>"); 46 } 47 out.println("</body>"); 48 out.println("</html>"); 49 } 50 }
编译上面的 Servlet DeleteCookies,并在 web.xml 文件中创建适当的条目。现在运行 http://localhost:8080/DeleteCookies,将显示如下结果:
现在尝试运行 http://localhost:8080/ReadCookies,它将只显示一个 cookie,如下所示:
您可以手动在 Internet Explorer 中删除 Cookies。在"工具"菜单,选择"Internet 选项"。如果要删除所有的 Cookies,请按"删除 Cookies"。
本文转载自:http://www.runoob.com/servlet/servlet-cookies-handling.html