1. 程式人生 > >javaWeb學習日記_19:cookie

javaWeb學習日記_19:cookie

1. Http協議與Cookie(瞭解)
  * Cookie是HTTP協議制定的!先由伺服器儲存Cookie到瀏覽器,再下次瀏覽器請求伺服器時把上一次請求得到Cookie再歸還給伺服器
  * 由伺服器建立儲存到客戶端瀏覽器的一個鍵值對!伺服器儲存Cookie的響應頭:Set-Cookie: aaa=AAA  Set-Cookie: bbb=BBB
    > response.addHeader("Set-Cookie", "aaa=AAA");response.addHeader("Set-Cookie", "bbb=BBB");
  * 當瀏覽器請求伺服器時,會把該伺服器儲存的Cookie隨請求傳送給伺服器。瀏覽器歸還Cookie的請求頭:Cookie: aaa=AAA; bbb=BBB
  * Http協議規定(保證不給瀏覽器太大壓力):


    > 1個Cookie最大4KB
    > 1個伺服器最多向1個瀏覽器儲存20個Cookie
    > 1個瀏覽器最多可以儲存300個Cookie
  * 瀏覽器大戰:因為瀏覽器競爭很激勵,所以很多瀏覽器都會在一定範圍內違反HTTP規定,但也不會讓一個Cookie為4GB!

2. Cookie的用途
  * 伺服器使用Cookie來跟蹤客戶端狀態!
  * 儲存購物車(購物車中的商品不能使用request儲存,因為它是一個使用者向伺服器傳送的多個請求資訊)
  * 顯示上次登入名(也是一個使用者多個請求)

  **********Cookie是不能跨瀏覽器的!***********

3. JavaWeb中使用Cookie
  * 原始方式(瞭解):
    > 使用response傳送Set-Cookie響應頭
    > 使用request獲取Cookie請求頭
  * 便捷方式(精通):
    > 使用repsonse.addCookie()方法向瀏覽器儲存Cookie
    > 使用request.getCookies()方法獲取瀏覽器歸還的Cookie

  Cookie第一例:
    > 一個jsp儲存cookie, a.jsp
    > 另一個jsp獲取瀏覽器歸還的cookie! b.jsp

4. Cookie詳解
  * Cookie不只有name和value兩個屬性
  * Cookie的maxAge(掌握):Cookie的最大生命,即Cookie可儲存的最大時長。以秒為單位,例如:cookie.setMaxAge(60)表示這個Cookie會被瀏覽器儲存到硬碟上60秒
    > maxAge>0:瀏覽器會把Cookie儲存到客戶機硬碟上,有效時長為maxAge的值決定。
    > maxAge<0:Cookie只在瀏覽器記憶體中存在,當用戶關閉瀏覽器時,瀏覽器程序結束,同時Cookie也就死亡了。
    > maxAge=0:瀏覽器會馬上刪除這個Cookie!

a.jsp:顯示Cookie的MaxAge<

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'a.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<h1>顯示Cookie的MaxAge</h1>
<%-- request、response、session、application、pageContext、config、out、page、exception --%>
<%
	Cookie cookie1 = new Cookie("aaa", "AAA");
	cookie1.setMaxAge(60*60);
	response.addCookie(cookie1);
%>
  </body>
</html>

b.jsp:刪除cookie

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'b.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<h1>刪除cookie</h1>
<%
Cookie cookie1 = new Cookie("aaa", "AAA");
cookie1.setMaxAge(0);
response.addCookie(cookie1);
%>
  </body>
</html>


  * Cookie的path(理解):
    > Cookie的path並不是設定這個Cookie在客戶端的儲存路徑!!!
    > Cookie的path由伺服器建立Cookie時設定
    > 當瀏覽器訪問伺服器某個路徑時,需要歸還哪些Cookie給伺服器呢?這由Cookie的path決定。
    > 瀏覽器訪問伺服器的路徑,如果包含某個Cookie的路徑,那麼就會歸還這個Cookie。
    > 例如:
      <> aCookie.path=/day11_1/; bCookie.path=/day11_1/jsps/; cCookie.path=/day11_1/jsps/cookie/;
      <> 訪問:/day11_1/index.jsp時,歸還:aCookie
      <> 訪問:/day11_1/jsps/a.jsp時,歸還:aCookie、bCookie
      <> 訪問:/day11_1/jsps/cookie/b.jsp時,歸還:aCookie、bCookie、cCookie
    > Cookie的path預設值:當前訪問路徑的父路徑。例如在訪問/day11_1/jsps/a.jsp時,響應的cookie,那麼這個cookie的預設path為/day11_1/jsps/
  * Cookie的domain(瞭解)
    > domain用來指定Cookie的域名!當多個二級域中共享Cookie時才有用。
    > 例如;www.baidu.com、zhidao.baidu.com、news.baidu.com、tieba.baidu.com之間共享Cookie時可以使用domain
    > 設定domain為:cookie.setDomain(".baidu.com");
    > 設定path為:cookie.setPath("/");


Cookie中不能存在中文!!!

// 儲存
Cookie c = new Cookie("username", URLEncoder.encode("張三", "utf-8"));//出錯!
response.addCookie(c);

// 獲取
Cookie[] cs = request.getCookies();
if(cs != null) {
  for(Cookie c : cs){
    if("username".equals(c.getName())) {
      String username = c.getValue();
      username = URLDecoder.decode(username, "utf-8");
    }
  }
}

例子:cookie的儲存和獲取

a.jsp:儲存

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'a.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<h1>儲存Cookie</h1>
<%-- request、response、session、application、pageContext、config、out、page、exception --%>
<%
	Cookie cookie1 = new Cookie("aaa", "AAA");
	response.addCookie(cookie1);
	
	Cookie cookie2 = new Cookie("bbb", "BBB");
	response.addCookie(cookie2);
%>
  </body>
</html>

b.jap:獲取cookie

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'b.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<h1>獲取Cookie</h1>
<%
	Cookie[] cookies = request.getCookies();
	if(cookies != null) {
		for(Cookie c : cookies) {
			out.print(c.getName() + "=" + c.getValue() + "<br/>");
		}
	}
%>
  </body>
</html>