您的位置 首页 php

Servlet Cookies 处理

cookie s 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息。Java servlet 显然支持 HTTP Cookies。

识别返回用户包括三个步骤:

  • 服务器脚本向浏览器发送一组 Cookies。例如:姓名、年龄或识别号码等。
  • 浏览器将这些信息存储在本地计算机上,以备将来使用。
  • 当下一次浏览器向 Web 服务器发送任何请求时,浏览器会把这些 Cookies 信息发送到服务器,服务器将使用这些信息来识别用户。

本章将向您讲解如何设置或重置 Cookies,如何访问它们,以及如何将它们删除。

Servlet Cookie 处理需要对中文进行编码与解码,方法如下:

String str = java.net.URLEncoder.encode("中文"); //编码
String str = java.net.URLDecoder.decode("编码后的字符串"); // 解码
 

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.cn
Connection: close
Content-Type: text/html
 

正如您所看到的,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 就能够通过请求方法 request .getCookies() 访问 Cookie,该方法将返回一个 Cookie 对象的数组。

Servlet Cookies 方法

以下是在 Servlet 中操作 Cookies 时可使用的有用的方法列表。

通过 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。

// 导入必需的 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");
 
 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><b>姓氏</b>:"
 + request.getParameter("last_name") + "\n" +
 "</ul>\n" +
 "</body></html>");
 }
}
 

编译上面的 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 目录中。当您访问 时,上面表单的实际输出如下所示:

尝试输入名字和姓氏,然后点击”提交”按钮,名字和姓氏将显示在屏幕上,同时会设置 firstName 和 lastName 这两个 Cookies,当下次您按下提交按钮时,会将这两个 Cookies 传回到服务器。

下一节会讲解如何在 Web 应用程序中访问这些 Cookies。

通过 Servlet 读取 Cookies

要读取 Cookies,您需要通过调用 HttpServletRequest getCookies( ) 方法创建一个 javax.servlet.http.Cookie 对象的数组。然后循环遍历数组,并使用 getName() 和 getValue() 方法来访问每个 cookie 和关联的值。

实例

让我们读取上面的实例中设置的 Cookies

// 导入必需的 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");
 
 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 class="tutheader">未找到 Cookies</h2>");
 }
 out.println("</body>");
 out.println("</html>");
 }
}
 

编译上面的 Servlet ReadCookies ,并在 web.xml 文件中创建适当的条目。如果您已经设置了 first_name cookie 为 “John”,last_name cookie 为 “Player” ,尝试运行 ,将显示如下结果:

查找 Cookies 名称和值

名称:first_name,值:John

名称:last_name,值:Player

通过 Servlet 删除 Cookies

删除 Cookies 是非常简单的。如果您想删除一个 cookie,那么您只需要按照以下三个步骤进行:

  • 读取一个现有的 cookie,并把它存储在 Cookie 对象中。
  • 使用 setMaxAge() 方法设置 cookie 的年龄为零,来删除现有的 cookie。
  • 把这个 cookie 添加到响应头。

实例

下面的例子将删除现有的名为 “first_name” 的 cookie,当您下次运行 ReadCookies 的 Servlet 时,它会返回 first_name 为空值。

// 导入必需的 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");
 
 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>");
 }
}
 

编译上面的 Servlet DeleteCookies ,并在 web.xml 文件中创建适当的条目。现在运行 ,将显示如下结果:

Cookies 名称和值

已删除的 cookie:first_name

名称:first_name,值:John

名称:last_name,值:Player

现在尝试运行 ,它将只显示一个 cookie,如下所示:

查找 Cookies 名称和值

名称:last_name,值:Player

您可以手动在 Internet Explorer 中删除 Cookies。在”工具”菜单,选择”Internet 选项”。如果要删除所有的 Cookies,请按”删除 Cookies”。

文章来源:智云一二三科技

文章标题:Servlet Cookies 处理

文章地址:https://www.zhihuclub.com/80362.shtml

关于作者: 智云科技

热门文章

网站地图