鍍金池/ 教程/ Java/ Cookies 處理
發(fā)送電子郵件
調(diào)試
異常處理
自動刷新頁面
處理日期
實例
生命周期
數(shù)據(jù)庫訪問
國際化
會話跟蹤
環(huán)境設(shè)置
客戶端 HTTP 請求
文件上傳
頁面重定向
服務(wù)器 HTTP 響應(yīng)
編寫過濾器
表單數(shù)據(jù)
HTTP 狀態(tài)碼
Cookies 處理
概述
點擊計數(shù)器

Cookies 處理

Cookies 是存儲在客戶端計算機上的文本文件,用于各種信息的跟蹤目的。Java Servlet 透明的支持 HTTP Cookies。

識別返回用戶包括以下三個步驟:

  • 服務(wù)器腳本向瀏覽器發(fā)送一組 cookies。例如姓名、年齡或身份證號碼等。

  • 瀏覽器將這些信息存儲在本地計算機中以備將來使用。

  • 當下次瀏覽器向 web 服務(wù)器發(fā)送任何請求時,它會把這些 cookies 信息發(fā)送到服務(wù)器,服務(wù)器使用這些信息來識別用戶。

本章教你如何設(shè)置或重置 cookies,如何訪問它們,以及如何刪除它們。

Cookie 剖析

通常情況下,Cookies 設(shè)置在 HTTP 頭信息中(盡管 JavaScript 也可以直接在瀏覽器上設(shè)置 cookie)。設(shè)置 cookie 的 servlet 可能會發(fā)送如下所示的頭信息:

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

正如你所看到的,Set-Cookie 頭信息包含了一個名稱值對、一個 GMT 日期、一個路徑和一個域。名稱和值會被 URL 編碼。有效期字段指示瀏覽器在給定的時間和日期之后“忘記”該 cookie。

如果瀏覽器被配置為存儲 cookies,它將會把這個信息保留到截止日期。如果用戶在任何與該 cookie 的路徑和域匹配的頁面點擊瀏覽器,它就會將這個 cookie 重新發(fā)送到服務(wù)器。瀏覽器的頭信息可能如下所示:

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 對象的數(shù)組。

Servlet Cookies 方法

以下是在 servlet 中操作 cookies 時你可能會用到的有用的方法列表。

序號 方法 & 描述
1

public void setDomain(String pattern)

該方法設(shè)置 cookie 適用的域,例如 tutorialspoint.com。

2

public String getDomain()

該方法獲取 cookie 適用的域,例如 tutorialspoint.com。

3

public void setMaxAge(int expiry)

該方法設(shè)置 cookie 過期的時間(以秒為單位)。如果不這樣設(shè)置,cookie 只會在當前 session 會話中持續(xù)有效。

4

public int getMaxAge()

該方法返回 cookie 的最大生存周期(以秒為單位),默認情況下,-1 表示 cookie 將持續(xù)下去,直到瀏覽器關(guān)閉。

5

public String getName()

該方法返回 cookie 的名稱。名稱在創(chuàng)建后不能改變。

6

public void setValue(String newValue)

該方法設(shè)置與 cookie 關(guān)聯(lián)的值。

7

public String getValue()

該方法獲取與 cookie 關(guān)聯(lián)的值。

8

public void setPath(String uri)

該方法設(shè)置 cookie 適用的路徑。如果您不指定路徑,與當前頁面相同目錄下的(包括子目錄下的)所有 URL 都會返回 cookie。

9

public String getPath()

該方法獲取 cookie 適用的路徑。

10

public void setSecure(boolean flag)

該方法設(shè)置布爾值,表示 cookie 是否應(yīng)該只在加密的(即 SSL)連接上發(fā)送。

11

public void setComment(String purpose)

該方法規(guī)定了描述 cookie 目的的注釋。該注釋在瀏覽器向用戶呈現(xiàn) cookie 時非常有用。

12

public String getComment()

該方法返回了描述 cookie 目的的注釋,如果 cookie 沒有注釋則返回 null。

用 Servlet 設(shè)置 Cookies

用 servlet 設(shè)置 cookies 包括三個步驟:

(1) 創(chuàng)建一個 Cookie 對象:用 cookie 名和 cookie 值調(diào)用 Cookie 構(gòu)造函數(shù),cookie 名和 cookie 值都是字符串。

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

記住,無論是名字還是值,都不應(yīng)該包含空格和以下任何字符:

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

(2) 設(shè)置最長有效期:你可以使用 setMaxAge 方法來指定 cookie 有效的時間(以秒為單位)。下面是設(shè)置了一個最長有效期為 24 小時的 cookie。

cookie.setMaxAge(60*60*24); 

(3) 發(fā)送 Cookie 到 HTTP 響應(yīng)頭:你可以使用 response.addCookie 來在 HTTP 響應(yīng)頭中添加 cookies,如下所示:

response.addCookie(cookie);

實例:

讓我們修改我們的 表單實例 來為姓名設(shè)置 cookies。

// 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 文件中創(chuàng)建適當?shù)臈l目,最后嘗試使用下述 HTML 頁面來調(diào)用 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 內(nèi)容保存到文件 hello.htm 中并把它放在 <Tomcat-installation-directory>/webapps/ROOT 目錄中。當你訪問 http://localhost:8080/Hello.htm 時,上述表單的實際輸出如下所示:

First Name:
Last Name:

嘗試輸入姓名,然后點擊提交按鈕。這將在你的屏幕上顯示姓名,同時會設(shè)置 firstName 和 lastName 這兩個 cookies,當下次你點擊提交按鈕時,會將這兩個 cookies 傳回到服務(wù)器。

下一節(jié)會解釋如何在你的 web 應(yīng)用程序中訪問這些 cookies。

用 Servlet 讀取 Cookies

要讀取 cookies,你需要通過調(diào)用 HttpServletRequestgetCookies( ) 方法創(chuàng)建一個 javax.servlet.http.Cookie 對象的數(shù)組。然后循環(huán)遍歷數(shù)組,并使用 getName() 和 getValue() 方法來訪問每個 cookie 及其相關(guān)的值。

實例

讓我們讀取上述例子中已經(jīng)設(shè)置的 cookies:

// 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 文件中創(chuàng)建適當?shù)臈l目。如果你已經(jīng)設(shè)置了 first name cookie 為 “John”,last name cookie 為 “Player” ,那么嘗試運行 http://localhost:8080/ReadCookies,將顯示如下所示結(jié)果:

Found Cookies Name and Value

Name : first_name, Value: John
Name : last_name, Value: Player

用 Servlet 刪除 Cookies

刪除 cookies 非常簡單。如果你想刪除一個 cookie,那么只需要按照如下所示的三個步驟進行:

  • 讀取一個現(xiàn)存的 cookie 并把它存儲在 Cookie 對象中。
  • 使用 setMaxAge() 方法設(shè)置 cookie 的年齡為零來刪除一個現(xiàn)存的 cookie。
  • 將這個 cookie 添加到響應(yīng)z中。

實例

下述例子將刪除一個現(xiàn)存的命名為 “first name” 的 cookie,且當你下次運行 ReadCookies servlet 時,它會為 first name 返回空值。

// 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 文件中創(chuàng)建適當?shù)臈l目。現(xiàn)在運行 http://localhost:8080/DeleteCookies,將顯示如下所示的結(jié)果:

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

現(xiàn)在嘗試運行 http://localhost:8080/ReadCookies,它將只顯示一個 cookie,如下所示:

Found Cookies Name and Value

Name : last_name, Value: Player

你可以在 IE 瀏覽器中手動刪除 Cookies。在“工具”菜單,選擇“Internet 選項”。如果要刪除所有的 cookies,請按刪除 Cookies。

上一篇:表單數(shù)據(jù)下一篇:文件上傳