Cookies 是存儲(chǔ)在客戶端計(jì)算機(jī)上的文本文件,并保留了各種跟蹤信息。Java Servlet 顯然支持 HTTP Cookies。
識(shí)別返回用戶包括三個(gè)步驟:
• 服務(wù)器腳本向?yàn)g覽器發(fā)送一組 Cookies。例如:姓名、年齡或識(shí)別號(hào)碼等。
• 瀏覽器將這些信息存儲(chǔ)在本地計(jì)算機(jī)上,以備將來(lái)使用。
• 當(dāng)下一次瀏覽器向 Web 服務(wù)器發(fā)送任何請(qǐng)求時(shí),瀏覽器會(huì)把這些 Cookies 信息發(fā)送到服務(wù)器,服務(wù)器將使用這些信息來(lái)識(shí)別用戶。
本章將向您講解如何設(shè)置或重置 Cookies,如何訪問它們,以及如何將它們刪除。
Servlet Cookie 處理需要對(duì)中文進(jìn)行編碼與解碼,方法如下:
String str = java.net.URLEncoder.encode("中文"); //編碼
String str = java.net.URLDecoder.decode("編碼后的字符串"); // 解碼
Cookie 剖析
Cookies 通常設(shè)置在 HTTP 頭信息中(雖然 JavaScript 也可以直接在瀏覽器上設(shè)置一個(gè) Cookie)。設(shè)置 Cookie 的 Servlet 會(huì)發(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=bjpowernode.com
Connection: close
Content-Type: text/html
正如您所看到的,Set-Cookie 頭包含了一個(gè)名稱值對(duì)、一個(gè) GMT 日期、一個(gè)路徑和一個(gè)域。名稱和值會(huì)被 URL 編碼。expires 字段是一個(gè)指令,告訴瀏覽器在給定的時(shí)間和日期之后"忘記"該 Cookie。
如果瀏覽器被配置為存儲(chǔ) Cookies,它將會(huì)保留此信息直到到期日期。如果用戶的瀏覽器指向任何匹配該 Cookie 的路徑和域的頁(yè)面,它會(huì)重新發(fā)送 Cookie 到服務(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 就能夠通過(guò)請(qǐng)求方法 request.getCookies() 訪問 Cookie,該方法將返回一個(gè) Cookie 對(duì)象的數(shù)組。
Servlet Cookies 方法
以下是在 Servlet 中操作 Cookies 時(shí)可使用的有用的方法列表。
序號(hào) |
方法 & 描述 |
---|---|
1 |
public void setDomain(String pattern) 該方法設(shè)置 cookie 適用的域,例如 bjpowernode.com。 |
2 |
public String getDomain() 該方法獲取 cookie 適用的域,例如 bjpowernode.com。 |
3 |
public void setMaxAge(int expiry) 該方法設(shè)置 cookie 過(guò)期的時(shí)間(以秒為單位)。如果不這樣設(shè)置,cookie 只會(huì)在當(dāng)前 session 會(huì)話中持續(xù)有效。 |
4 |
public int getMaxAge() 該方法返回 cookie 的最大生存周期(以秒為單位),默認(rèn)情況下,-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 適用的路徑。如果您不指定路徑,與當(dāng)前頁(yè)面相同目錄下的(包括子目錄下的)所有 URL 都會(huì)返回 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 時(shí)非常有用。 |
12 |
public String getComment() 該方法返回了描述 cookie 目的的注釋,如果 cookie 沒有注釋則返回 null。 |
通過(guò) Servlet 設(shè)置 Cookies
通過(guò) Servlet 設(shè)置 Cookies 包括三個(gè)步驟:
1. 創(chuàng)建一個(gè) Cookie 對(duì)象:您可以調(diào)用帶有 cookie 名稱和 cookie 值的 Cookie 構(gòu)造函數(shù),cookie 名稱和 cookie 值都是字符串。
Cookie cookie = new Cookie("key","value");
請(qǐng)記住,無(wú)論是名字還是值,都不應(yīng)該包含空格或以下任何字符:
[ ] ( ) = , " / ? @ : ;
2.設(shè)置最大生存周期:您可以使用 setMaxAge 方法來(lái)指定 cookie 能夠保持有效的時(shí)間(以秒為單位)。下面將設(shè)置一個(gè)最長(zhǎng)有效期為 24 小時(shí)的 cookie。
cookie.setMaxAge(60*60*24);
3. 發(fā)送 Cookie 到 HTTP 響應(yīng)頭:您可以使用 response.addCookie 來(lái)添加 HTTP 響應(yīng)頭中的 Cookies,如下所示:
response.addCookie(cookie);
實(shí)例
讓我們修改我們的 表單數(shù)據(jù)實(shí)例,為名字和姓氏設(shè)置 Cookies。
// 導(dǎo)入必需的 java 庫(kù)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 擴(kuò)展 HttpServlet 類
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// 為名字和姓氏創(chuàng)建 Cookies
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
// 為兩個(gè) Cookies 設(shè)置過(guò)期日期為 24 小時(shí)后
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// 在響應(yīng)頭中添加兩個(gè) Cookies
response.addCookie( firstName );
response.addCookie( lastName );
// 設(shè)置響應(yīng)內(nèi)容類型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "設(shè)置 Cookies 實(shí)例";
String docType =
"<!doctype html public \"-//bjpowernode//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 文件中創(chuàng)建適當(dāng)?shù)臈l目,最后嘗試下面的 HTML 頁(yè)面來(lái)調(diào)用 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 內(nèi)容到文件 hello.htm 中,并把它放在 <Tomcat-installation-directory> /webapps/ROOT 目錄中。當(dāng)您訪問 http://localhost:8080/Hello.htm 時(shí),上面表單的實(shí)際輸出如下所示:
嘗試輸入名字和姓氏,然后點(diǎn)擊"提交"按鈕,名字和姓氏將顯示在屏幕上,同時(shí)會(huì)設(shè)置 firstName 和 lastName 這兩個(gè) Cookies,當(dāng)下次您按下提交按鈕時(shí),會(huì)將這兩個(gè) Cookies 傳回到服務(wù)器。
下一節(jié)會(huì)講解如何在 Web 應(yīng)用程序中訪問這些 Cookies。
通過(guò) Servlet 讀取 Cookies
要讀取 Cookies,您需要通過(guò)調(diào)用 HttpServletRequest 的 getCookies( ) 方法創(chuàng)建一個(gè) javax.servlet.http.Cookie 對(duì)象的數(shù)組。然后循環(huán)遍歷數(shù)組,并使用 getName() 和 getValue() 方法來(lái)訪問每個(gè) cookie 和關(guān)聯(lián)的值。
實(shí)例
讓我們讀取上面的實(shí)例中設(shè)置的 Cookies
// 導(dǎo)入必需的 java 庫(kù)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 擴(kuò)展 HttpServlet 類
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// 獲取與該域相關(guān)的 Cookies 的數(shù)組
cookies = request.getCookies();
// 設(shè)置響應(yīng)內(nèi)容類型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
String docType =
"<!doctype html public \"-//bjpowernode//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 文件中創(chuàng)建適當(dāng)?shù)臈l目。如果您已經(jīng)設(shè)置了 first_name cookie 為 "John",last_name cookie 為 "Player" ,嘗試運(yùn)行 http://localhost:8080/ReadCookies,將顯示如下結(jié)果:
查找 Cookies 名稱和值
名稱:first_name,值:John
名稱:last_name,值:Player
通過(guò) Servlet 刪除 Cookies
刪除 Cookies 是非常簡(jiǎn)單的。如果您想刪除一個(gè) cookie,那么您只需要按照以下三個(gè)步驟進(jìn)行:
• 讀取一個(gè)現(xiàn)有的 cookie,并把它存儲(chǔ)在 Cookie 對(duì)象中。
• 使用 setMaxAge() 方法設(shè)置 cookie 的年齡為零,來(lái)刪除現(xiàn)有的 cookie。
• 把這個(gè) cookie 添加到響應(yīng)頭。
實(shí)例
下面的例子將刪除現(xiàn)有的名為 "first_name" 的 cookie,當(dāng)您下次運(yùn)行 ReadCookies 的 Servlet 時(shí),它會(huì)返回 first_name 為空值。
// 導(dǎo)入必需的 java 庫(kù)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 擴(kuò)展 HttpServlet 類
public class DeleteCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// 獲取與該域相關(guān)的 Cookies 的數(shù)組
cookies = request.getCookies();
// 設(shè)置響應(yīng)內(nèi)容類型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";
String docType =
"<!doctype html public \"-//bjpowernode//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 文件中創(chuàng)建適當(dāng)?shù)臈l目。現(xiàn)在運(yùn)行 http://localhost:8080/DeleteCookies,將顯示如下結(jié)果:
Cookies 名稱和值
已刪除的 cookie:first_name
名稱:first_name,值:John
名稱:last_name,值:Player
現(xiàn)在嘗試運(yùn)行 http://localhost:8080/ReadCookies,它將只顯示一個(gè) cookie,如下所示:
查找 Cookies 名稱和值
名稱:last_name,值:Player
您可以手動(dòng)在 Internet Explorer 中刪除 Cookies。在"工具"菜單,選擇"Internet 選項(xiàng)"。如果要?jiǎng)h除所有的 Cookies,請(qǐng)按"刪除 Cookies"。