Cookies 是存儲在客戶端計算機上的文本文件,用于各種信息的跟蹤目的。Java Servlet 透明的支持 HTTP Cookies。
識別返回用戶包括以下三個步驟:
服務(wù)器腳本向瀏覽器發(fā)送一組 cookies。例如姓名、年齡或身份證號碼等。
瀏覽器將這些信息存儲在本地計算機中以備將來使用。
本章教你如何設(shè)置或重置 cookies,如何訪問它們,以及如何刪除它們。
通常情況下,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 時你可能會用到的有用的方法列表。
序號 | 方法 & 描述 |
---|---|
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 包括三個步驟:
(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
時,上述表單的實際輸出如下所示:
嘗試輸入姓名,然后點擊提交按鈕。這將在你的屏幕上顯示姓名,同時會設(shè)置 firstName 和 lastName 這兩個 cookies,當下次你點擊提交按鈕時,會將這兩個 cookies 傳回到服務(wù)器。
下一節(jié)會解釋如何在你的 web 應(yīng)用程序中訪問這些 cookies。
要讀取 cookies,你需要通過調(diào)用 HttpServletRequest 的 getCookies( ) 方法創(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
刪除 cookies 非常簡單。如果你想刪除一個 cookie,那么只需要按照如下所示的三個步驟進行:
下述例子將刪除一個現(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目?,F(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。
更多建議: