Servlet-Cookies处理


Cookies是存储在客户端计算机上的文本文件,它们被保留以用于各种信息跟踪目的。Java Servlet透明地支持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 = csdn.net
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: csdn.net
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz

然后,Servlet将通过请求方法request.getCookies()来访问Cookie,该方法返回一个Cookie对象数组。

扫描二维码关注公众号,回复: 10345098 查看本文章

Servlet Cookies方法

以下是在servlet中处理cookie时可以使用的有用方法的列表:

方法 说明
public void setDomain(String pattern) 此方法设置cookie适用的域,例如csdn.net。
public String getDomain() 此方法获取cookie适用的域,例如csdn.net。
public void setMaxAge(int expiry) 此方法设置cookie过期之前应经过的时间(以秒为单位)。如果没有设置,默认cookie仅在当前会话中持续存在。
public int getMaxAge() 此方法返回cookie的最长使用期限(以秒为单位)。默认情况下,-1表示cookie将持续到浏览器关闭为止。
public String getName() 此方法返回cookie的名称。创建后不能更改名称。
public void setValue(String newValue) 此方法设置与cookie关联的值
public String getValue() 此方法获取与cookie关联的值。
public void setPath(String uri) 此方法设置此cookie所应用的路径。如果您未指定路径,则会为与当前页面相同的目录中的所有URL以及所有子目录返回cookie。
public String getPath() 此方法获取此cookie所应用的路径。
public void setSecure(boolean flag) 此方法设置布尔值,该值指示是否仅应通过加密(即SSL)连接发送cookie。
public void setComment(String purpose) 此方法指定描述cookie用途的注释。如果浏览器向用户显示cookie,则该注释很有用。
public String getComment() 此方法返回描述此cookie用途的注释;如果cookie没有注释,则返回null。

使用Servlet设置Cookie

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

  1. 创建一个Cookie对象 :调用coonkie构造函数创建Cookie:Cookie cookie = new Cookie("key","value");
  2. 设置最长期限:可以使用setMaxAge指定cookie有效的时间(以秒为单位)。例如设置一个24小时的Cookie:cookie.setMaxAge(60 * 60 * 24);
  3. 将Cookie发送到HTTP响应标头中:使用response.addCookie在HTTP响应标头中添加cookie,如下所示:response.addCookie(cookie);

    让我们修改“ Servlet-表单数据”的代码来设置名字和姓氏的cookie。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class HelloForm extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // 创建姓和名的cookie     
      Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

      //设置最长期限为24小时
      firstName.setMaxAge(60*60*24);
      lastName.setMaxAge(60*60*24);

      //发送Cookie到http响应标头
      response.addCookie( firstName );
      response.addCookie( lastName );

      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
      String title = "设置Cookie";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
      
      out.println(docType +
         "<html>\n" +
            "<head>\n<title>" + title + "</title>\n</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>\n" +
         "</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按钮时传递回服务器。

使用Servlet读取Cookie

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

例如让我们阅读我们在上一个示例中设置的cookie:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class ReadCookies extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      Cookie cookie = null;
      Cookie[] cookies = null;

      //获取cookie
      cookies = request.getCookies();

      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "读取Cookie";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " +
         "transitional//en\">\n";
         
      out.println(docType +
         "<html>\n" +
         "<head>\n<title>" + title + "</title>\n</head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" );

      if( cookies != null ) {
         out.println("<h2>获取到Cookie</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>没有找到Cookie</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

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

使用Servlet删除Cookies

删除Cookie非常简单。如果您想删除Cookie,则只需遵循以下三个步骤:

  • 读取一个已经存在的cookie并将其存储在Cookie对象中。
  • 使用setMaxAge()方法将Cookie年龄设为零,以删除现有的Cookie
  • 将此Cookie重新添加到响应标头中。

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

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class DeleteCookies extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      Cookie cookie = null;
      Cookie[] cookies = null;
         
      //获取cookie
      cookies = request.getCookies();

      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>\n<title>" + title + "</title>\n</head>\n" +
         "<body bgcolor = \"#f0f0f0\">\n" );
         
      if( cookies != null ) {
         out.println("<h2>获取到Cookie</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>找不到cookie</h2>");
      }
      out.println("</body>");
      out.println("</html>");
   }
}

在Servlet DeleteCookies上方进行编译,并在web.xml文件中创建适当的条目。现在运行http://localhost:8080/DeleteCookies将显示以下结果:
在这里插入图片描述
现在尝试运行http://localhost:8080/ReadCookies,它将仅显示一个cookie,如下所示:
在这里插入图片描述
上一篇:Servlet-异常
下一篇:Servlet-Session跟踪

发布了49 篇原创文章 · 获赞 17 · 访问量 5310

猜你喜欢

转载自blog.csdn.net/JAVA_php_Jack/article/details/104255398