JSP - Cookie 處理



本章將討論 JSP 中的 Cookie 處理。Cookie 是儲存在客戶端計算機上的文字檔案,用於各種資訊跟蹤目的。JSP 使用底層的 Servlet 技術透明地支援 HTTP Cookie。

識別和返回使用者涉及三個步驟:

  • 伺服器指令碼向瀏覽器傳送一組 Cookie。例如,姓名、年齡或識別號等。

  • 瀏覽器將此資訊儲存在本地機器上以備將來使用。

  • 下次瀏覽器向 Web 伺服器傳送任何請求時,它會將這些 Cookie 資訊傳送到伺服器,伺服器使用這些資訊來識別使用者,或者也可能用於其他目的。

本章將教你如何使用 JSP 程式設定或重置 Cookie、如何訪問它們以及如何刪除它們。

Cookie 的構成

Cookie 通常設定在 HTTP 頭中(儘管 JavaScript 也可以直接在瀏覽器上設定 Cookie)。設定 Cookie 的 JSP 可能會發送如下所示的標頭:

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 編碼。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

然後,JSP 指令碼可以透過 request 方法request.getCookies()訪問 Cookie,該方法返回一個 Cookie 物件陣列。

Servlet Cookie 方法

下表列出了與 Cookie 物件相關的有用方法,你可以在 JSP 中操作 Cookie 時使用:

序號 方法和描述
1

public void setDomain(String pattern)

此方法設定 Cookie 應用到的域;例如,tutorialspoint.com。

2

public String getDomain()

此方法獲取 Cookie 應用到的域;例如,tutorialspoint.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 應用到的路徑。如果你不指定路徑,則 Cookie 將返回與當前頁面相同的目錄中的所有 URL 以及所有子目錄。

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。

使用 JSP 設定 Cookie

使用 JSP 設定 Cookie 涉及三個步驟:

步驟 1:建立 Cookie 物件

你使用 Cookie 名稱和 Cookie 值(都是字串)呼叫 Cookie 建構函式。

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

請記住,名稱和值都不應包含空格或以下任何字元:

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

步驟 2:設定最大年齡

你使用setMaxAge指定 Cookie 應有效的時長(以秒為單位)。以下程式碼將設定一個 Cookie 持續 24 小時。

cookie.setMaxAge(60*60*24); 

步驟 3:將 Cookie 傳送到 HTTP 響應頭

你使用response.addCookie在 HTTP 響應頭中新增 Cookie,如下所示

response.addCookie(cookie);

示例

讓我們修改我們的表單示例以設定名字和姓氏的 Cookie。

<%
   // 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 );
%>

<html>
   <head>
      <title>Setting Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Setting Cookies</h1>
      </center>
      <ul>
         <li><p><b>First Name:</b>
            <%= request.getParameter("first_name")%>
         </p></li>
         <li><p><b>Last  Name:</b>
            <%= request.getParameter("last_name")%>
         </p></li>
      </ul>
   
   </body>
</html>

讓我們將以上程式碼放在main.jsp檔案中,並在以下 HTML 頁面中使用它:

<html>
   <body>
      
      <form action = "main.jsp" 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.jsp的檔案中,並將hello.jspmain.jsp放在<Tomcat-安裝目錄>/webapps/ROOT目錄中。當你訪問https://:8080/hello.jsp時,以下是上述表單的實際輸出。

名字
姓氏

嘗試輸入名字和姓氏,然後點選提交按鈕。這將在你的螢幕上顯示名字和姓氏,並將設定兩個 Cookie firstNamelastName。下次你點選提交按鈕時,這些 Cookie 將被傳回伺服器。

在下一節中,我們將解釋如何在你 Web 應用程式中訪問這些 Cookie。

使用 JSP 讀取 Cookie

要讀取 Cookie,你需要透過呼叫HttpServletRequestgetCookies( )方法建立一個javax.servlet.http.Cookie物件的陣列。然後遍歷陣列,並使用getName()getValue()方法訪問每個 Cookie 及其關聯的值。

示例

現在讓我們讀取在前面示例中設定的 Cookie:

<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         Cookie cookie = null;
         Cookie[] cookies = null;
         
         // Get an array of Cookies associated with the this domain
         cookies = request.getCookies();
         
         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>");
         }
      %>
   </body>
   
</html>

現在讓我們將上述程式碼放在main.jsp檔案中並嘗試訪問它。如果你將first_name Cookie設定為“John”,將last_name Cookie設定為“Player”,則執行https://:8080/main.jsp將顯示以下結果:

Found Cookies Name and Value

Name : first_name, Value: John

Name : last_name, Value: Player

使用 JSP 刪除 Cookie

刪除 Cookie 非常簡單。如果你想刪除 Cookie,你只需按照以下三個步驟操作:

  • 讀取已存在的 Cookie 並將其儲存在 Cookie 物件中。

  • 使用setMaxAge()方法將 Cookie 年齡設定為零以刪除現有 Cookie。

  • 將此 Cookie 添加回響應頭。

示例

下面的示例將向你展示如何刪除名為“first_name”的現有 Cookie,下次執行 main.jsp JSP 時,它將返回 first_name 的 null 值。

<html>
   <head>
      <title>Reading Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Reading Cookies</h1>
      </center>
      <%
         Cookie cookie = null;
         Cookie[] cookies = null;
         
         // Get an array of Cookies associated with the this domain
         cookies = request.getCookies();
         
         if( cookies != null ) {
            out.println("<h2> Found 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>");
         }
      %>
   </body>
   
</html>

現在讓我們將上述程式碼放在main.jsp檔案中並嘗試訪問它。它將顯示以下結果:

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

現在再次執行https://:8080/main.jsp,它應該只顯示一個 Cookie,如下所示:

Found Cookies Name and Value

Name : last_name, Value: Player

你可以在 Internet Explorer 中手動刪除 Cookie。從“工具”選單開始,選擇“Internet 選項”。要刪除所有 Cookie,請單擊“刪除 Cookie”按鈕。

廣告