Cookie機(jī)制
前言會(huì)話跟蹤是Web程序中常用的技術(shù),用來(lái)跟蹤用戶的整個(gè)會(huì)話。常用的會(huì)話跟蹤技術(shù)是Cookie和session。Cookie通過在客戶端記錄信息確定用戶身份,Session通過在服務(wù)器端記錄信息確定用戶身份。今天,我首先給大家講解一下Cookie機(jī)制,后面我會(huì)給大家提到Session的。
什么是CookieWeb應(yīng)用程序是使用HTTP協(xié)議傳輸數(shù)據(jù)的。HTTP協(xié)議是無(wú)狀態(tài)的協(xié)議。一旦數(shù)據(jù)交換完畢,客戶端與服務(wù)器端的連接就會(huì)關(guān)閉,再次交換數(shù)據(jù)需要新的連接。這就意味著服務(wù)器無(wú)法從連接上跟蹤會(huì)話。即用戶A購(gòu)買了一件商品放入購(gòu)物車內(nèi),當(dāng)再次購(gòu)買商品時(shí)服務(wù)器已經(jīng)無(wú)法判斷該購(gòu)買行為是屬于用戶A的會(huì)話還是用戶B的會(huì)話。所以,要跟蹤會(huì)話,我們必須引入一種機(jī)制。此時(shí),我們就給客戶端們頒發(fā)一個(gè)通行證,無(wú)論誰(shuí)訪問都必須出示通行證也就是身份卡。這樣服務(wù)器就可以通過這個(gè)身份卡辨別出身份了。這就是Cookie的工作原理。
我們還可以查看網(wǎng)站頒發(fā)的Cookie,只需要在網(wǎng)址欄中輸入javascript:alert(document.cookie)就可以了。

Java中把Cookie封裝成了javax.servlet.http.Cookie類。每個(gè)Cookie都是該Cookie類的對(duì)象。服務(wù)器通過操作Cookie對(duì)象來(lái)對(duì)客戶端Cookie進(jìn)行操作,通過request.getCookie()獲取客戶端提交的所有Cookie,通過response.addCookie(Cookie cookie)向客戶端設(shè)置Cookie。
Cookie對(duì)象使用key-value屬性對(duì)的形式保存用戶狀態(tài),一個(gè)Cookie對(duì)象保存一個(gè)屬性對(duì),一個(gè)request或者response同時(shí)使用多個(gè)Cookie。
以下代碼就是使用Cookie來(lái)記錄用戶賬號(hào)以及登陸次數(shù)的例子。
1 <%@ page import="java.util.Date" %> 2 <%@ page import="java.text.SimpleDateFormat" %> 3 <%-- 4 Created by IntelliJ IDEA. 5 User: Administrator 6 Date: 2015/6/17 7 Time: 11:58 8 To change this template use File | Settings | File Templates. 9 --%>10 <%@ page contentType="text/html;charset=UTF-8" language="java" %>11 <%12 request.setCharacterEncoding("UTF-8");13 14 String username = "";15 int visitTimes = 0;16 17 Cookie[] cookies = request.getCookies();18 19 for (int i = 0; cookies != null && i < cookies.length; i++) {20 Cookie cookie = cookies[i];21 if ("username".equals(cookie.getName())) {22 username = cookie.getValue();23 } else if ("visitTimes".equals(cookie.getName())) {24 visitTimes = Integer.parseInt(cookie.getValue());25 }26 }27 if (username == null || username.trim().equals("")) {28 throw new Exception("請(qǐng)先登錄");29 }30 Cookie visitTimesCookie = new Cookie("visitTimes",Integer.toString(++visitTimes));31 response.addCookie(visitTimesCookie);32 %>33 <html>34 <head>35 <title></title>36 </head>37 <body>38 <div align="center" style="margin:10px; ">39 <fieldset>40 <legend>登錄信息 當(dāng)前時(shí)間:<%= new Date() %></legend>41 <form action="login.jsp" method="post">42 <table>43 <tr>44 <td>您的賬號(hào): </td>45 <td><%= username %></td>46 </tr>47 <tr>48 <td>登錄次數(shù): </td>49 <td><%= visitTimes %></td>50 </tr>51 <tr>52 <td></td>53 <td>54 <input type="button" value="刷 新" onclick="location='<%=request.getRequestURI()%>?ts=' + new55 Date().getTime(); " class="button">56 </td>57 </tr>58 </table>59 </form>60 </fieldset>61 </div>62 </body>63 </html>如果沒有找到包含username屬性的Cookie,則拋出異常,頁(yè)面跳轉(zhuǎn)到登陸頁(yè)面login.jsp。
1 <%-- 2 Created by IntelliJ IDEA. 3 User: Administrator 4 Date: 2015/6/17 5 Time: 12:14 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <%10 request.setCharacterEncoding("UTF-8");11 response.setCharacterEncoding("UTF-8");12 13 if ("POST".equals(request.getMethod())) {14 Cookie usernameCookie = new Cookie("username",request.getParameter("username"));15 Cookie visitTimesCookie = new Cookie("visitTimes","0");16 17 response.addCookie(usernameCookie);18 response.addCookie(visitTimesCookie);19 20 response.sendRedirect(request.getContextPath() + "/cookie.jsp");21 return ;22 }23 %>24 <html>25 <head>26 <title>請(qǐng)先登錄</title>27 </head>28 <body>29 <div align="center" style="margin:10px; ">30 <fieldset>31 <legend>登錄</legend>32 <form action="login.jsp" method="post">33 <table>34 <tr>35 <td>賬號(hào): </td>36 <td><input type="text" name="username" style="width:200px; "></td>37 </tr>38 <tr>39 <td>密碼: </td>40 <td><input type="passWord" name="password" style="width:200px; "</td>41 </tr>42 <tr>43 <td></td>44 <td><input type="submit" value="登 錄" class="button"</td>45 </tr>46 </table>47 </form>48 </fieldset>49 </div>50 </body>51 </html>另外,Cookie還具有以下一些特點(diǎn):
下面的程序使用UTF-8編碼了Cookie內(nèi)容,然后再使用UTF-8解碼Cookie并顯示出來(lái)。
1 <%-- 2 Created by IntelliJ IDEA. 3 User: Administrator 4 Date: 2015/6/17 5 Time: 13:41 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <jsp:directive.page import="java.net.URLEncoder"/>10 <jsp:directive.page import="java.net.URLDecoder"/>11 <%12 Cookie cookie = new Cookie(13 URLEncoder.encode("姓名","UTF-8"),14 URLEncoder.encode("天才白癡夢(mèng)","UTF-8"));15 response.addCookie(cookie);16 %>17 <html>18 <head>19 <title>Cookie Encoding</title>20 </head>21 <body>22 <%23 if (request.getCookies() != null) {24 for (Cookie cc : request.getCookies()) {25 String cookieName = URLDecoder.decode(cc.getName(),"UTF-8");26 String cookieValue = URLDecoder.decode(cc.getValue(),"UTF-8");27 28 out.PRintln(cookieName + " : " + cookieValue + "; <br/>");29 }30 }31 else {32 out.println("Cookie 已經(jīng)寫入客戶端,請(qǐng)刷新頁(yè)面。");33 }34 %>35 </body>36 </html>
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注