JavaWeb学习总结第五篇--认识Cookie机制

Cookie机制

前言

会话跟踪是Web程序中常用的技术,用来跟踪用户的整个会话。常用的会话跟踪技术是CookieSession。Cookie通过在客户端记录信息确定用户身份,Session通过在服务器端记录信息确定用户身份。今天,我首先给大家讲解一下Cookie机制,后面我会给大家提到Session的。

什么是Cookie

Web应用程序是使用HTTP协议传输数据的。HTTP协议是无状态的协议。一旦数据交换完毕,客户端与服务器端的连接就会关闭,再次交换数据需要新的连接。这就意味着服务器无法从连接上跟踪会话。即用户A购买了一件商品放入购物车内,当再次购买商品时服务器已经无法判断该购买行为是属于用户A的会话还是用户B的会话。所以,要跟踪会话,我们必须引入一种机制。此时,我们就给客户端们颁发一个通行证,无论谁访问都必须出示通行证也就是身份卡。这样服务器就可以通过这个身份卡辨别出身份了。这就是Cookie的工作原理。

我们还可以查看网站颁发的Cookie,只需要在网址栏中输入javascript:alert(document.cookie)就可以了。

记录用户访问次数

Java中把Cookie封装成了javax.servlet.http.Cookie类。每个Cookie都是该Cookie类的对象。服务器通过操作Cookie对象来对客户端Cookie进行操作,通过request.getCookie()获取客户端提交的所有Cookie,通过response.addCookie(Cookie cookie)向客户端设置Cookie。

Cookie对象使用key-value属性对的形式保存用户状态,一个Cookie对象保存一个属性对,一个request或者response同时使用多个Cookie。

以下代码就是使用Cookie来记录用户账号以及登陆次数的例子。

 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("请先登录");
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>登录信息  当前时间:<%= new Date() %></legend>
41         <form action="login.jsp" method="post">
42           <table>
43             <tr>
44               <td>您的账号: </td>
45               <td><%= username %></td>
46             </tr>
47             <tr>
48               <td>登录次数: </td>
49               <td><%= visitTimes %></td>
50             </tr>
51             <tr>
52               <td></td>
53               <td>
54                 <input type="button" value="刷 新" onclick="location='<%=request.getRequestURI()%>?ts=' + new
55                         Date().getTime(); " class="button">
56               </td>
57             </tr>
58           </table>
59         </form>
60       </fieldset>
61     </div>
62   </body>
63 </html>

如果没有找到包含username属性的Cookie,则抛出异常,页面跳转到登陆页面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>请先登录</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>账号: </td>
36               <td><input type="text" name="username" style="200px; "></td>
37             </tr>
38             <tr>
39               <td>密码: </td>
40               <td><input type="password" name="password" style="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还具有以下一些特点:

  • 不可跨域名性,Google和Baidu的Cookie是分开的,各自访问时显示的是各自的Cookie。
  • Cookie中保存中文只能编码
  • Cookie中可以保存二进制数据,比如使用数字证书

下面的程序使用UTF-8编码了Cookie内容,然后再使用UTF-8解码Cookie并显示出来。

 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("天才白痴梦","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 已经写入客户端,请刷新页面。");
33       }
34     %>
35   </body>
36 </html>

 

原文地址:https://www.cnblogs.com/BaiYiShaoNian/p/4583116.html