zoukankan      html  css  js  c++  java
  • 会话技术之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;
                     100%;
                }
                .carousel-inner .item img {
                     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="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="1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
                <h4 style=" 50%;float: left;font: 14px/30px " 微软雅黑 ";">浏览记录<small>
                                       <a href="/CookieSession/clearHistory">清空</a></small></h4> <div style=" 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=" 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 {
                     100%;
                    height: 300px;
                }
            </style>
        </head>
        <body>
            <div class="col-md-6">
                <div><strong>衣服</strong></div>
                <div style="border-bottom: 1px dotted #dddddd;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;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;127px;" value="加入购物车" type="button"> </a> &nbsp;收藏商品</div> </div> </div> <div class="clear"></div> <div style="950px;margin:0 auto;"> <div style="background-color:#d3d3d3;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 {
                     100%;
                    height: 300px;
                }
            </style>
        </head>
    
        <body>
            <div class="container">
                <div class="row">
                    <div style="margin:0 auto;950px;">
                        <div class="col-md-6">
                            <div><strong>眼镜</strong></div>
                            <div style="border-bottom: 1px dotted #dddddd;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;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;127px;" value="加入购物车" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="950px;margin:0 auto;"> <div style="background-color:#d3d3d3;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 {
                     100%;
                    height: 300px;
                }
            </style>
        </head>
    
        <body>
            <div class="container">
                <div class="row">
                    <div style="margin:0 auto;950px;">
                        <div class="col-md-6">
                            <div><strong>包</strong></div>
                            <div style="border-bottom: 1px dotted #dddddd;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;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;127px;" value="加入购物车" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="950px;margin:0 auto;"> <div style="background-color:#d3d3d3;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 {
                     100%;
                    height: 300px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="row">
                    <div style="margin:0 auto;950px;">
                        
                        <div class="col-md-6">
                            <div><strong>手机</strong></div>
                            <div style="border-bottom: 1px dotted #dddddd;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;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;127px;" value="加入购物车" type="button"> </a> &nbsp;收藏商品</div> </div> </div> </div> <div class="clear"></div> <div style="950px;margin:0 auto;"> <div style="background-color:#d3d3d3;930px;padding:10px 10px;margin:10px 0 10px 0;"> <strong>商品介绍</strong> </div> <div> <img src="img/cs10004.jpg" style="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;
                     100%;
                }
                .carousel-inner .item img {
                     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="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="1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
                <h4 style=" 50%;float: left;font: 14px/30px " 微软雅黑 ";">浏览记录<small>
                                  <a href="/CookieSession/clearHistory">清空</a></small></h4> <div style=" 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=" 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中不支持中文
  • 相关阅读:
    javamail.providers not found
    vue.js实现购物车功能2.0版本
    vue.js实现购物车功能
    iframe高度自适应
    C语言 自定义字符串拼接函数
    php安装
    Apache安装
    python:爬虫初体验
    c:forEach 显示下拉框并回显
    数据结构 --- 线性表学习(php模拟)
  • 原文地址:https://www.cnblogs.com/hejh/p/11024010.html
Copyright © 2011-2022 走看看