目录

Servlets - Cookie处理( Cookies Handling)

Cookie是存储在客户端计算机上的文本文件,用于各种信息跟踪目的。 Java Servlets透明地支持HTTP cookie。

确定回归用户涉及三个步骤 -

  • 服务器脚本将一组cookie发送到浏览器。 例如姓名,年龄或身份证号码等。

  • 浏览器将此信息存储在本地计算机上以供将来使用

  • 当下次浏览器向Web服务器发送任何请求时,它会将这些cookie信息发送到服务器,服务器使用该信息来识别用户。

本章将教您如何设置或重置cookie,如何访问它们以及如何删除它们。

Cookie的剖析

Cookie通常设置在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 = iowiki.com
Connection: close
Content-Type: text/html

如您所见,Set-Cookie标头包含名称值对,GMT日期,路径和域。 名称和值将进行URL编码。 expires字段是浏览器在给定时间和日期之后“忘记”cookie的指令。

如果浏览器配置为存储cookie,则会将此信息保留到有效期。 如果用户将浏览器指向与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 Cookie方法

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

Sr.No. 方法和描述
1

public void setDomain(String pattern)

此方法设置cookie适用的域,例如iowiki.com。

2

public String getDomain()

此方法获取cookie适用的域,例如iowiki.com。

3

public void setMaxAge(int expiry)

此方法设置cookie到期之前应经过多长时间(以秒为单位)。 如果您未设置此值,则cookie将仅持续当前会话。

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设置Cookie

使用servlet设置cookie涉及三个步骤 -

(1) Creating a Cookie object - 使用cookie名称和cookie值调用Cookie构造函数,两者都是字符串。

Cookie cookie = new Cookie("key","value");

请记住,名称和值都不应包含空格或以下任何字符 -

[ ] ( ) = , "/? @ : ;

(2) Setting the maximum age - 使用setMaxAge指定cookie应该有效的时间长度(以秒为单位)。 以下将设置一个24小时的cookie。

cookie.setMaxAge(60 * 60 * 24); 

(3) Sending the Cookie into the HTTP response headers - 您使用response.addCookie在HTTP响应头中添加cookie,如下所示 -

response.addCookie(cookie);

例子 (Example)

我们修改Form Example以设置名字和姓名的cookie。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      // Create cookies for first and last names.      
      Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
      // Set expiry date after 24 Hrs for both the cookies.
      firstName.setMaxAge(60*60*24);
      lastName.setMaxAge(60*60*24);
      // Add both the cookies in the response header.
      response.addCookie( firstName );
      response.addCookie( lastName );
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Setting 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" +
               "<h1 align = \"center\">" + title + "</h1>\n" +
               "<ul>\n" +
                  "  <li><b>First Name</b>: "
                  + request.getParameter("first_name") + "\n" +
                  "  <li><b>Last Name</b>: "
                  + request.getParameter("last_name") + "\n" +
               "</ul>\n" +
            "</body>
         </html>"
      );
   }
}

编译上面的servlet HelloForm并在web.xml文件中创建适当的条目,最后尝试按照HTML页面调用servlet。

 
<html>
   <body>
      <form action = "HelloForm" method = "GET">
         First Name: <input type = "text" name = "first_name">
         <br />
         Last Name: <input type = "text" name = "last_name" />
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

将HTML内容保存在文件Hello.htm中,并将其放在/webapps/ROOT目录中。 当您访问http://localhost:8080/Hello.htm ,以下是上述表单的实际输出。

名字: 姓:

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

下一节将向您解释如何在Web应用程序中访问这些cookie。

用Servlet读取Cookies

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

例子 (Example)

让我们读一下我们在前面的例子中设置的cookie -

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ReadCookies extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      Cookie cookie = null;
      Cookie[] cookies = null;
      // Get an array of Cookies associated with this domain
      cookies = request.getCookies();
      // Set response content type
      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> Found Cookies Name and Value</h2>");
         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( ) + " <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

编译上面的servlet ReadCookies并在web.xml文件中创建适当的条目。 如果您将first_name cookie设置为“John”并将last_name cookie设置为“Player”,则运行http://localhost:8080/ReadCookies将显示以下结果 -

<h2> Found Cookies Name and Value</h2>
Name : first_name, Value: John 
Name : last_name,  Value: Player

使用Servlet删除Cookies

删除cookie非常简单。 如果您想删除cookie,那么您只需要按照以下三个步骤进行操作 -

  • 读取已存在的cookie并将其存储在Cookie对象中。

  • 使用setMaxAge()方法将cookie年龄设置为零以删除现有cookie

  • 将此cookie添加回响应头。

例子 (Example)

以下示例将删除名为“first_name”的现有cookie,并在下次运行ReadCookies servlet时为first_name返回null值。

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      Cookie cookie = null;
      Cookie[] cookies = null;
      // Get an array of Cookies associated with this domain
      cookies = request.getCookies();
      // Set response content type
      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 Name and Value</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("Deleted cookie : " + cookie.getName( ) + "<br/>");
            }
            out.print("Name : " + cookie.getName( ) + ",  ");
            out.print("Value: " + cookie.getValue( )+" <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

编译上面的servlet DeleteCookies并在web.xml文件中创建适当的条目。 现在运行http://localhost:8080/DeleteCookies将显示以下结果 -

<h2>Cookies Name and Value</h2>
<p>Deleted cookie : first_name</p>
<p>Name : first_name, Value: John</p>
<p>Name : last_name,  Value: Player</p>

现在尝试运行http://localhost:8080/ReadCookies ,它将只显示一个cookie,如下所示 -

<h2> Found Cookies Name and Value</h2>
Name : last_name,  Value: Player

您可以手动删除Internet Explorer中的cookie。 从“工具”菜单开始,然后选择“Internet选项”。 要删除所有cookie,请按Delete Cookies。

↑回到顶部↑
WIKI教程 @2018