會話技術之cookie(記錄當前時間、瀏覽記錄的記錄和清除)


cookie

 

會話技術:
  當用戶打開瀏覽器的時候,訪問不同的資源,直到用戶將瀏覽器關閉,可以認為這是一次會話.
作用:
   因為http協議是一個無狀態的協議,它不會記錄上一次訪問的內容.用戶在訪問過程中難免會產生一些數據,通過會話技術就可以將數據保存起來.

    例如:
      用戶登錄
      驗證碼
      購物車
      訪問記錄

會話技術分類:
    cookie:瀏覽器端會話技術
    session:服務器端會話技術

 

cookie: 小餅干 小甜點 cookie是由服務器生成,通過response將cookie寫回瀏覽器(set-cookie),保留在瀏覽器上, 下一次訪問,瀏覽器根據一定的規則攜帶不同的cookie(通過request的頭 cookie),我們服務器就可以接受cookie
 cookie的api: new Cookie(String key,String value) 寫回瀏覽器: response.addCookie(Cookie c) 獲取cookie: Cookie[] request.getCookies() cookie的常用方法: getName():獲取cookie的key(名稱) getValue:獲取指定cookie的值

 

 cookie小案例:

 

   web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation=
      "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <servlet> <servlet-name>HelloCookieServlet</servlet-name> <servlet-class>com.hjh.cookie.HelloCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloCookieServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>

   

HelloCookieServlet.java源碼
package com.hjh.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * cookie入門 */
public class HelloCookieServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼:
        response.setContentType("text/html;charset=utf-8"); //創建一個cookie
        Cookie c1= new Cookie("user1","hjh"); //通過response寫回到瀏覽器中
 response.addCookie(c1); //提示信息
        response.getWriter().print("cookie已經寫回"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

   啟動項目,第一次發送請求,在firefox瀏覽器中按f12鍵查看cookie,request中是沒有cookie的,但是response中有cookie信息,如下圖:

   第二次發送請求,再次查看cookie信息,request和response中都有cookie,且是同一個cookie,如下圖:

   

 

  擴展-創建多個cookie:在前一個案例基礎上,替換以下代碼即可,

//創建多個cookie
Cookie c1= new Cookie("user1","hjh"); Cookie c2= new Cookie("user2","sss"); Cookie c3= new Cookie("user3","qqq"); //通過response寫回到瀏覽器中
response.addCookie(c1); response.addCookie(c2); response.addCookie(c3);

    啟動項目,第一次發送請求,在firefox瀏覽器中按f12鍵查看cookie,request中是沒有cookie的,但是response中有cookie信息,如下圖:

   第二次發送請求,再次查看cookie信息,request和response中都有cookie,且是同一個cookie,如下圖:

 

 

  案例:

案例1-步驟分析: 1.創建一個serlvet RemServlet 路徑:/rem 2.在servlet中: 獲取指定cookie 例如:名稱為 lastTime request.getCookies() 判斷cookie是否為空 若為空:提示信息 第一次訪問 若不為空: 獲取此cookie的value 展示信息:你上次訪問時間是.... 將這次訪問時間記錄,寫會瀏覽器

  web.xml配置:

<servlet>
    <servlet-name>RemServlet</servlet-name>
    <servlet-class>com.hjh.cookie.RemServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RemServlet</servlet-name>
    <url-pattern>/rem</url-pattern>
  </servlet-mapping>
RemServlet.java源碼
package com.hjh.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 記錄上次訪問時間 */
public class RemServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼
        response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); //1.獲取指定名稱的cookie;request.getCookies()獲取的為步驟3時創建的cookie
        Cookie c = getCookieByName("lastTime",request.getCookies()); //2.判斷cookie是否為空
        if(c==null) { //cookie為空(第一次訪問),提示 歡迎新用戶訪問本系統
            writer.print("歡迎新用戶訪問本系統"); }else { //cookie不為空(第二次及之后訪問),獲取value,展示上一次訪問的時間
            String value = c.getValue(); long time = Long.parseLong(value); Date date = new Date(time); writer.print("您上次訪問時間為:"+date.toLocaleString()); } //持久化cookie
        if(c!=null) { c.setMaxAge(3600); //設置路徑
            c.setPath(request.getContentType()+"/"); } /*3.將當前訪問時間記錄寫回瀏覽器(第一次訪問,創建cookie; 第2次及以后的訪問,都是將c指向更新了時間之后的cookie)*/ c = new Cookie("lastTime",new Date().getTime()+""); response.addCookie(c); } private Cookie getCookieByName(String name, Cookie[] cookies) { if(cookies!=null) { for (Cookie cookie : cookies) { if(name.equals(cookie.getName())) { return cookie; } } } return null; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

  第一次訪問,頁面顯示如下:

  刷新頁面再次訪問,頁面顯示上次訪問該項目的時間,頁面顯示如下:

 

 

cookie-總結: 常用方法: setMaxAge(int 秒):設置cookie在瀏覽器端存活時間 以秒為單位 若設置成 0:刪除該cookie(前提必須路徑一致) setPath(String path):設置cookie的路徑. 當我們訪問的路徑中包含此cookie的path,則攜帶 默認路徑: 訪問serlvet的路徑,從"/項目名稱"開始,到最后一個"/"結束 例如: 訪問的serlvet路徑: /day11/a/b/hello 默認路徑為: /day11/a/b 手動設置路徑:以"/項目名"開始,以"/"結尾;

 

 

案例2:記錄用戶瀏覽歷史

需求:
    當用戶訪問一個商品的時候,需要將該商品保留在瀏覽記錄中
技術分析:
    cookie
步驟分析: 1.先將product_list.htm轉成jsp 2.點擊一個商品,展示該商品的信息,將該商品id記錄到cookie (GetProductById) 獲取之前的瀏覽記錄 例如名稱:ids 判斷cookie是否為空 若為空 將當前商品的id起個名稱 ids 放入cookie中 ids=1 若不為空,獲取cookie當前值 例如:ids=2-1;使用"-"分割商品id; 若當前訪問的id=1 ,判斷之前記錄中有無該商品 若有: 將當前的id放入前面 結果 ids=1-2 若沒有: 繼續判斷長度是否>=3>=3,移除最后一個,將當前的id放入最前面 若<3,直接將當前的id放入最前面. 若 ids=3-2-1 現在訪問1 結果 ids=1-3-2 若 ids=4-3-2 現在訪問1 結果 ids=1-4-3

    3.再次回到product_list.jsp頁面,需要將之前訪問商品展示在瀏覽記錄中 獲取ids 例如:ids=2-3-1 切割

   web.xml配置:

 <servlet>
    <servlet-name>GetProductByIdServlet</servlet-name>
    <servlet-class>com.hjh.session.GetProductByIdServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetProductByIdServlet</servlet-name>
    <url-pattern>/getProductById</url-pattern>
  </servlet-mapping>
GetProductByIdServlet.java源碼:
package com.hjh.session; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hjh.utils.CookieUtils; public class GetProductByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.獲取訪問商品的id
        String id = request.getParameter("id"); //2.獲取指定的cookie ids
        Cookie cookie = CookieUtils.getCookieByName("ids", request.getCookies()); //3.判斷cookie是否存在
        String ids = ""; if(cookie==null) { //cookie為空,需要將當前訪問的商品id放入ids中
            ids = id; }else { //cookie不為空,繼續判斷當前訪問商品id是否在ids中存在;ids以2-4-7形式存在 //獲取名為ids的cookie的值
            ids= cookie.getValue(); //將ids進行切割,便於比較當前訪問商品id是否存在於ids中
            String[] arr = ids.split("-"); //將數組轉成集合,此list長度不可變
            List<String> asList = Arrays.asList(arr); //將asList放入一個新的list集合中
            LinkedList<String> list = new LinkedList<>(asList); //判斷商品id是否存在ids中
            if(list.contains(id)){ //若ids中包含id,將id移除,並在list最前面加上此id
 list.remove(id); list.addFirst(id); }else { //若ids中不存在id,繼續判斷長度是否大於2
                if(list.size()>2) { //長度>=3,移除最后一個,並將當前id放入list最前面
 list.removeLast(); list.addFirst(id); }else{ //長度<3,將當前id放入list最前面
 list.addFirst(id); } } ids = ""; //將list轉成字符串(即ids)
            for(String s:list) { ids+=(s+"-"); } ids=ids.substring(0, ids.length()-1); }//cookie不為空 //將ids寫回去
        cookie = new Cookie("ids",ids); response.addCookie(cookie); //設置訪問路徑
        cookie.setPath(request.getContextPath()+"/"); //設置cookie存活時間
        cookie.setMaxAge(3600); //重定向跳轉
        response.sendRedirect(request.getContextPath()+"/product_info"+id+".htm"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } 
CookieUtils.java源碼:
package com.hjh.utils; import javax.servlet.http.Cookie; public class CookieUtils { public static Cookie getCookieByName(String name, Cookie[] cookies) { if(cookies!=null) { for (Cookie cookie : cookies) { if(name.equals(cookie.getName())) { return cookie; } } } return null; } }

  product_list.jsp

<%@page import="com.hjh.utils.CookieUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!doctype html>
<html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        

        <style> body { margin-top: 20px; margin: 0 auto; width: 100%; } .carousel-inner .item img { width: 100%; height: 300px; } .row{ height:280px; } .col-md-2{ float:left; margin-right: 100px; margin-left:10px; margin-top:10px; } </style>
    </head>

    <body>
    
        <div class="row" style="width:1210px;margin:0 auto;">

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=1">
                    <img src="./img/cs10001.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=1" style='color:green'>衣服</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=2">
                    <img src="img/cs10002.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=2" style='color:green'>眼鏡</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=3">
                    <img src="img/cs10003.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=3" style='color:green'>包</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=4">
                    <img src="img/cs10004.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=4" style='color:green'>手機</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>
            
        </div>

        <!-- 商品瀏覽記錄: -->
        <div style="width:1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
            <h4 style="width: 50%;float: left;font: 14px/30px " 微軟雅黑 ";">瀏覽記錄<small>
                                   <a href="/CookieSession/clearHistory">清空</a></small></h4> <div style="width: 50%;float: right;text-align: right;"><a href="">more</a></div> <div style="clear: both;"></div> <div style="overflow: hidden;"> <ul style="list-style: none;"> <% //獲取指定名稱的cookie Cookie cookie=CookieUtils.getCookieByName("ids", request.getCookies()); //判斷id是否為空 if(cookie==null){ %> <h2>暫無瀏覽記錄</h2> <% }else{//ids=3-2-5 String [] arr=cookie.getValue().split("-"); for(String id:arr){ %> <li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;
                   text-align: center;"><img src="img/cs1000<%=id %>.jpg" width="130px" height="130px" /></li> <% } } %> </ul> </div> </div> </body> </html>

  product_info1.htm:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
    </head>
    <body>
        <div class="col-md-6">
            <div><strong>衣服</strong></div>
            <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
                <div>編號:751</div>
            </div>
            <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:100元/件</strong> 
                                              參 考 價: <del>¥99.00元/件</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0;;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="cart.htm"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);
                                  height:36px;width:127px;" value="加入購物車" type="button"> </a> &nbsp;收藏商品</div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10001.jpg"> </div> </div> </body> </html>

  product_info2.htm:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
    </head>

    <body>
        <div class="container">
            <div class="row">
                <div style="margin:0 auto;width:950px;">
                    <div class="col-md-6">
                        <div><strong>眼鏡</strong></div>
                        <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
                            <div>編號:751</div>
                        </div>
                        <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:200元/件</strong> 
                                              參 考 價: <del>¥199.00元/件</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                                ;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="cart.htm"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                          rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10002.jpg"> </div> </div> </div> </div> </body> </html>

   product_info3.htm:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
    </head>

    <body>
        <div class="container">
            <div class="row">
                <div style="margin:0 auto;width:950px;">
                    <div class="col-md-6">
                        <div><strong>包</strong></div>
                        <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
                            <div>編號:751</div>
                        </div>
                        <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:300元/份</strong> 
                                             參 考 價: <del>¥299.00元/份</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                                ;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="cart.htm"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                          rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10003.jpg"> </div> </div> </div> </div> </body> </html>

  product_info4.htm:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div style="margin:0 auto;width:950px;">
                    
                    <div class="col-md-6">
                        <div><strong>手機</strong></div>
                        <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
                            <div>編號:751</div>
                        </div>
                        <div style="margin:10px 0 10px 0;">億家價: <strong style="color:#ef0101;">¥:400元/份</strong> 
                                              參 考 價: <del>¥388.00元/份</del> </div> <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                              ;background-color: #fffee6;"> <div style="margin:5px 0 10px 0;">白色</div> <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">購買數量: <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div> <div style="margin:20px 0 10px 0;;text-align: center;"> <a href="cart.htm"> <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                          rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入購物車" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="width:950px;margin:0 auto;"> <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介紹</strong> </div> <div> <img src="img/cs10004.jpg" style="width:300px"> </div> </div> </div> </div> </body> </html>

   啟動項目,輸入如下url,回車,在沒有點擊下面4張圖片時,瀏覽記錄為空,如下圖:

   先點擊眼鏡這張圖,然后點擊包這張圖,返回product_list.jsp頁面,刷新,瀏覽記錄顯示如圖:

 

 

 

擴展:刪除瀏覽記錄

技術分析: cookie.setMaxAge(0)
步驟分析: 1.在瀏覽器記錄中添加一個超鏈接 <a href="/day1101/clearHistroy">清空</a>
    2.創建servlet clearHistroy 創建一個cookie 名稱路徑保持一致 setMaxAge(0) 寫回瀏覽器 3.頁面跳轉 重定向 product_list.jsp

 

   web.xml配置:

<servlet>
    <servlet-name>ClearHistoryServlet</servlet-name>
    <servlet-class>com.hjh.session.ClearHistoryServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ClearHistoryServlet</servlet-name>
    <url-pattern>/clearHistory</url-pattern>
  </servlet-mapping>
ClearHistoryServlet.java源碼:
package com.hjh.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hjh.utils.CookieUtils; public class ClearHistoryServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //創建一個cookie
        Cookie cookie = CookieUtils.getCookieByName("ids", request.getCookies()); cookie.setPath(request.getContextPath()+"/"); //設置時間為0,即清空cookie
        cookie.setMaxAge(0); //寫回瀏覽器
 response.addCookie(cookie); //頁面跳轉
        response.sendRedirect(request.getContextPath()+"/product_list.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

    product_list.jsp:

<%@page import="com.hjh.utils.CookieUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <style> body { margin-top: 20px; margin: 0 auto; width: 100%; } .carousel-inner .item img { width: 100%; height: 300px; } .row{ height:280px; } .col-md-2{ float:left; margin-right: 100px; margin-left:10px; margin-top:10px; } </style>
    </head>

    <body>
        <div class="row" style="width:1210px;margin:0 auto;">
            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=1">
                    <img src="./img/cs10001.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=1" style='color:green'>衣服</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>
            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=2">
                    <img src="img/cs10002.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=2" style='color:green'>眼鏡</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=3">
                    <img src="img/cs10003.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=3" style='color:green'>包</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>

            <div class="col-md-2">
                <a href="/CookieSession/getProductById?id=4">
                    <img src="img/cs10004.jpg" width="170" height="170" style="display: inline-block;">
                </a>
                <p><a href="/CookieSession/getProductById?id=4" style='color:green'>手機</a></p>
                <p><font color="#FF0000">商城價:&yen;299.00</font></p>
            </div>
            
        </div>

        <!-- 商品瀏覽記錄: -->
        <div style="width:1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
            <h4 style="width: 50%;float: left;font: 14px/30px " 微軟雅黑 ";">瀏覽記錄<small>
                              <a href="/CookieSession/clearHistory">清空</a></small></h4> <div style="width: 50%;float: right;text-align: right;"><a href="">more</a></div> <div style="clear: both;"></div> <div style="overflow: hidden;"> <ul style="list-style: none;"> <% //獲取指定名稱的cookie Cookie cookie=CookieUtils.getCookieByName("ids", request.getCookies()); //判斷id是否為空 if(cookie==null){ %> <h2>暫無瀏覽記錄</h2> <% }else{//ids=3-2-5 String [] arr=cookie.getValue().split("-"); for(String id:arr){ %> <li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;
                  text-align: center;"><img src="img/cs1000<%=id %>.jpg" width="130px" height="130px" /></li> <% } } %> </ul> </div> </div> </body> </html>

   啟動項目,輸入url,點擊眼鏡的圖片,返回product_list.jsp頁面,瀏覽記錄里顯示剛才的眼鏡的記錄,如下圖:

 

   點擊清空按鈕,瀏覽記錄中提示“暫無瀏覽記錄”提示語,清空瀏覽記錄在IE、firefox瀏覽器有效,在google瀏覽器中沒有效果:

 

 

 

注意:
    cookie不能跨瀏覽器
    cookie中不支持中文

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM