Cookie 其實是存儲在客戶端上的文本信息,並保留了各類跟蹤的信息。
Cookie工做步驟:
(1)客戶端請求服務器,若是服務器須要記錄該用戶的狀態,就是用 response 向客戶端瀏覽器頒發一個 Cookie。
(2)客戶端瀏覽器會把 Cookie 保存下來。
(3)當瀏覽器再請求該網站時,瀏覽器把該請求的網址連同 Cookie 一同提交給服務器。服務器檢查該 Cookie,以此來辨認用戶狀態。
注:Cookie功能須要瀏覽器的支持,若是瀏覽器不支持Cookie或者Cookie禁用了,Cookie功能就會失效。
Java中把Cookie封裝成了javax.servlet.http.Cookie類。
Cookies 一般設置在 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=w3cschool.cc
Connection: close
Content-Type: text/html
|
正如您所看到的,Set-Cookie 頭包含了一個名稱值對、一個 GMT 日期、一個路徑和一個域。名稱和值會被 URL 編碼。expires 字段是一個指令,告訴瀏覽器在給定的時間和日期以後"忘記"該 Cookie。
若是瀏覽器被配置爲存儲 Cookies,它將會保留此信息直到到期日期。若是用戶的瀏覽器指向任何匹配該 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
|
方法
|
功能
|
public void setDomain(String pattern)
|
該方法設置 cookie 適用的域。
|
public String getDomain()
|
該方法獲取 cookie 適用的域。
|
public void setMaxAge(int expiry)
|
該方法設置 cookie 過時的時間(以秒爲單位)。若是不這樣設置,cookie 只會在當前 session 會話中持續有效。
|
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)
|
該方法設置布爾值,向瀏覽器指示,只會在HTTPS和SSL等安全協議中傳輸此類Cookie。
|
public void setComment(String purpose)
|
該方法規定了描述 cookie 目的的註釋。該註釋在瀏覽器向用戶呈現 cookie 時很是有用。
|
public String getComment()
|
該方法返回了描述 cookie 目的的註釋,若是 cookie 沒有註釋則返回 null。
|
Cookie的maxAge決定着Cookie的有效期,單位爲秒。
若是maxAge爲0,則表示刪除該Cookie;若是爲負數,表示該Cookie僅在本瀏覽器中以及本窗口打開的子窗口內有效,關閉窗口後該Cookie即失效。
Cookie中提供getMaxAge()和setMaxAge(int expiry)方法來讀寫maxAge屬性。
Cookie是不能夠跨域名的。域名www.google.com頒發的Cookie不會被提交到域名www.baidu.com去。這是由Cookie的隱私安全機制決定的。隱私安全機制可以禁止網站非法獲取其餘網站的Cookie。
正常狀況下,同一個一級域名的兩個二級域名之間也不能互相使用Cookie。若是想讓某域名下的子域名也可使用該Cookie,須要設置Cookie的domain參數。
Java中使用setDomain(String domain)和getDomain()方法來設置、獲取domain。
Path屬性決定容許訪問Cookie的路徑。
Java中使用setPath(String uri)和getPath()方法來設置、獲取path。
HTTP協議不只是無狀態的,並且是不安全的。
使用HTTP協議的數據不通過任何加密就直接在網絡上傳播,有被截獲的可能。若是不但願Cookie在HTTP等非安全協議中傳輸,能夠設置Cookie的secure屬性爲true。瀏覽器只會在HTTPS和SSL等安全協議中傳輸此類Cookie。
Java中使用setSecure(boolean flag)和getSecure ()方法來設置、獲取Secure。
經過 Servlet 添加 Cookies 包括三個步驟:
(1)建立一個 Cookie 對象:您能夠調用帶有 cookie 名稱和 cookie 值的 Cookie 構造函數,cookie 名稱和 cookie 值都是字符串。
(2)設置最大生存週期:您可使用 setMaxAge 方法來指定 cookie 可以保持有效的時間(以秒爲單位)。
(3)發送 Cookie 到 HTTP 響應頭:您可使用 response.addCookie 來添加 HTTP 響應頭中的 Cookies。
AddCookieDemo.java
package notes.javaee.servlet.cookie;
// 導入必需的 java 庫
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 擴展 HttpServlet 類
@WebServlet("/servlet/cookie/addCookieDemo")
public class AddCookieDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookieName = new Cookie("name", request.getParameter("name"));
Cookie cookieAge = new Cookie("age", request.getParameter("age"));
// 爲兩個Cookie設置有效期
cookieName.setMaxAge(30);
cookieAge.setMaxAge(30);
// 在響應頭中添加兩個 Cookies
response.addCookie(cookieName);
response.addCookie(cookieAge);
// 設置響應內容類型
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
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><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>名字</b>:"
+ request.getParameter("name") + "\n" +
" <li><b>年齡</b>:"
+ request.getParameter("age") + "\n" +
"</ul>\n" +
"</body></html>");
}
}
|
ShowCookieDemo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>顯示Cookie</title>
</head>
<body>
<form action="/ServletNotes/servlet/cookie/showCookieDemo"method="GET">
名字:<input type="text" name="name">
<br />
年齡:<input type="text" name="age"/>
<input type="submit"value="提交" />
</form>
</body>
</html>
|
訪問http://localhost:8080/ServletNotes/ShowCookieDemo.html,提交輸入文本後,能夠看到cookie內容。
要讀取 Cookies,您須要經過調用 HttpServletRequest的getCookies()方法建立一個 javax.servlet.http.Cookie對象的數組。而後循環遍歷數組,並使用 getName() 和 getValue() 方法來訪問每一個 cookie 和關聯的值。
ReadCookies.java
package notes.javaee.servlet.cookie;
// 導入必需的 java 庫
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
// 擴展 HttpServlet 類
@WebServlet("/servlet/cookie/readCookies")
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// 獲取與該域相關的 Cookies 的數組
cookies = request.getCookies();
// 設置響應內容類型
response.setContentType("text/html;charset=UTF-8");
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>查找 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>未找到 Cookies</h2>");
}
out.println("</body>");
out.println("</html>");
}
}
|
Java中並無提供直接刪除Cookie的方法,若是想要刪除一個Cookie,直接將這個Cookie的有效期設爲0就能夠了。步驟以下:
(1)讀取一個現有的 cookie,並把它存儲在 Cookie 對象中。
(2)使用 setMaxAge() 方法設置 cookie 的年齡爲零,來刪除現有的 cookie。
(3)把這個 cookie 添加到響應頭。
DeleteCookieDemo.java
package notes.javaee.servlet.cookie;
// 導入必需的 java 庫
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 擴展 HttpServlet 類
@WebServlet("/servlet/cookie/deleteCookieDemo")
public class DeleteCookieDemoextends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = null;
Cookie[] cookies = null;
// 獲取與該域相關的 Cookies 的數組
cookies = request.getCookies();
// 設置響應內容類型
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
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 名稱和值</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if ((cookie.getName()).compareTo("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>");
}
} |