Cookie 是存儲(chǔ)在客戶端計(jì)算機(jī)上的文本文件,并保留了各種跟蹤信息。Java Servlet 顯然支持 HTTP Cookie。
識(shí)別返回用戶包括三個(gè)步驟:
服務(wù)器腳本向?yàn)g覽器發(fā)送一組 Cookie。例如:姓名、年齡或識(shí)別號(hào)碼等。
瀏覽器將這些信息存儲(chǔ)在本地計(jì)算機(jī)上,以備將來(lái)使用。
當(dāng)下一次瀏覽器向 Web 服務(wù)器發(fā)送任何請(qǐng)求時(shí),瀏覽器會(huì)把這些 Cookie 信息發(fā)送到服務(wù)器,服務(wù)器將使用這些信息來(lái)識(shí)別用戶。
本章將向您講解如何設(shè)置或重置 Cookie,如何訪問(wèn)它們,以及如何將它們刪除。
Servlet Cookie 處理需要對(duì)中文進(jìn)行編碼與解碼,方法如下:
String str = java.net.URLEncoder.encode("中文","UTF-8"); //編碼 String str = java.net.URLDecoder.decode("編碼后的字符串","UTF-8"); // 解碼
Cookie 通常設(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=(cainiaoplus.com) Connection: close Content-Type: text/html
正如您所看到的,Set-Cookie 頭包含了一個(gè)名稱值對(duì)、一個(gè) GMT 日期、一個(gè)路徑和一個(gè)域。名稱和值會(huì)被 URL 編碼。expires 字段是一個(gè)指令,告訴瀏覽器在給定的時(shí)間和日期之后"忘記"該 Cookie。
如果瀏覽器被配置為存儲(chǔ) Cookie,它將會(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() 訪問(wèn) Cookie,該方法將返回一個(gè) Cookie 對(duì)象的數(shù)組。
以下是在 Servlet 中操作 Cookie 時(shí)可使用的有用的方法列表。
序號(hào) | 方法 & 描述 |
---|---|
1 | public void setDomain(String pattern) 該方法設(shè)置 cookie 適用的域,例如 (cainiaoplus.com)。 |
2 | public String getDomain() 該方法獲取 cookie 適用的域,例如 (cainiaoplus.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) 設(shè)置cookie的注釋。該注釋在瀏覽器向用戶呈現(xiàn) cookie 時(shí)非常有用。 |
12 | public String getComment() 獲取 cookie 的注釋,如果 cookie 沒(méi)有注釋則返回 null。 |
通過(guò) Servlet 設(shè)置 Cookie 包括三個(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)頭中的 Cookie,如下所示:
response.addCookie(cookie);
讓我們修改我們的 表單數(shù)據(jù)示例,為名字和姓氏設(shè)置 Cookie。
package com.nhooo.test; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; 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; /** * Servlet implementation class HelloServlet */ @WebServlet("/HelloForm") public class HelloForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloForm() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 為名字和姓氏創(chuàng)建 Cookie Cookie name = new Cookie("name", URLEncoder.encode(request.getParameter("name"), "UTF-8")); // 中文轉(zhuǎn)碼 Cookie url = new Cookie("url", request.getParameter("url")); // 為兩個(gè) Cookie 設(shè)置過(guò)期日期為 24 小時(shí)后 name.setMaxAge(60*60*24); url.setMaxAge(60*60*24); // 在響應(yīng)頭中添加兩個(gè) Cookie response.addCookie( name ); response.addCookie( url ); // 設(shè)置響應(yīng)內(nèi)容類型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "設(shè)置 Cookie 示例"; String docType = "<!DOCTYPE html>\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>站點(diǎn)名:</b>:" + request.getParameter("name") + "\n</li>" + " <li><b>站點(diǎn) URL:</b>:" + request.getParameter("url") + "\n</li>" + "</ul>\n" + "</body></html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
編譯上面的 Servlet HelloForm,并在 web.xml 文件中創(chuàng)建適當(dāng)?shù)臈l目:
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <!-- 類名 --> <servlet-name>HelloForm</servlet-name> <!-- 所在的包 --> <servlet-class>com.nhooo.test.HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <!-- 訪問(wèn)的網(wǎng)址 --> <url-pattern>/TomcatTest/HelloForm</url-pattern> </servlet-mapping> </web-app>
最后嘗試下面的 HTML 頁(yè)面來(lái)調(diào)用 Servlet。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥(niǎo)教程(cainiaoplus.com)</title> </head> <body> <form action="/TomcatTest/HelloForm" method="GET"> 站點(diǎn)名 :<input type="text" name="name"> <br /> 站點(diǎn) URL:<input type="text" name="url" /><br> <input type="submit" value="提交" /> </form> </body> </html>
保存上面的 HTML 內(nèi)容到文件 /TomcatTest/test.html 中。
接下來(lái)我們?cè)L問(wèn)http://localhost:8080/TomcatTest/test.html,演示如下:
點(diǎn)“提交”后,效果如下:
注意:以上的一些路徑需要根據(jù)你項(xiàng)目實(shí)際路徑修改。
要讀取 Cookie,您需要通過(guò)調(diào)用 HttpServletRequest 的 getCookies( ) 方法創(chuàng)建一個(gè) javax.servlet.http.Cookie 對(duì)象的數(shù)組。然后循環(huán)遍歷數(shù)組,并使用 getName() 和 getValue() 方法來(lái)訪問(wèn)每個(gè) cookie 和關(guān)聯(lián)的值。
讓我們讀取上面的示例中設(shè)置的 Cookie
package com.nhooo.test; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; 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; /** * Servlet implementation class ReadCookies */ @WebServlet("/ReadCookies") public class ReadCookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ReadCookies() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // 獲取與該域相關(guān)的 Cookie 的數(shù)組 cookies = request.getCookies(); // 設(shè)置響應(yīng)內(nèi)容類型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Delete Cookie Example"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2>Cookie 名稱和值</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("參數(shù)名:" + cookie.getName( ) + ","); out.print("參數(shù)值:" + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br/>"); } }else{ out.println( "<h2 class=\"tutheader\">No Cookie founds</h2>"); } out.println("</body>"); out.println("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
編譯上面的 Servlet ReadCookies,并在 web.xml 文件中創(chuàng)建適當(dāng)?shù)臈l目。嘗試運(yùn)行 http://localhost:8080/TomcatTest/ReadCookies,將顯示如下結(jié)果:
刪除 Cookie 是非常簡(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)有的名為 "url" 的 cookie,當(dāng)您下次運(yùn)行 ReadCookies 的 Servlet 時(shí),它會(huì)返回 url 為 null。
package com.nhooo.test; 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; /** * Servlet implementation class DeleteCookies */ @WebServlet("/DeleteCookies") public class DeleteCookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeleteCookies() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // 獲取與該域相關(guān)的 Cookie 的數(shù)組 cookies = request.getCookies(); // 設(shè)置響應(yīng)內(nèi)容類型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "刪除 Cookie 示例"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2>Cookie 名稱和值</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("url") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("已刪除的 cookie:" + cookie.getName( ) + "<br/>"); } out.print("參數(shù)名:" + cookie.getName( ) + ","); out.print("參數(shù)值:" + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2 class=\"tutheader\">No Cookie founds</h2>"); } out.println("</body>"); out.println("</html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
編譯上面的 Servlet DeleteCookies,并在 web.xml 文件中創(chuàng)建適當(dāng)?shù)臈l目?,F(xiàn)在運(yùn)行 http://localhost:8080/TomcatTest/DeleteCookies,將顯示如下結(jié)果: