cookie

  1. 会话技术:
      当用户打开浏览器的时候,访问不同的资源,直到用户将浏览器关闭,可以认为这是一次会话.

  2. 作用:
       因为http协议是一个无状态的协议,它不会记录上一次访问的内容.用户在访问过程中难免会产生一些数据,通过会话技术就可以将数据保存起来.

    例如:
      用户登录
      验证码
      购物车
      访问记录

  1. 会话技术分类:
  2. cookie:浏览器端会话技术
  3. session:服务器端会话技术
  1. cookie:
  2. 小饼干 小甜点
  3. cookie是由服务器生成,通过responsecookie写回浏览器(set-cookie),保留在浏览器上,
  4. 下一次访问,浏览器根据一定的规则携带不同的cookie(通过request的头 cookie),我们服务器就可以接受cookie
  1. cookieapi:
  2. new Cookie(String key,String value)
  3. 写回浏览器:
  4. response.addCookie(Cookie c)
  5. 获取cookie:
  6. Cookie[] request.getCookies()
  7. cookie的常用方法:
  8. getName():获取cookiekey(名称)
  9. getValue:获取指定cookie的值

cookie小案例:

   web.xml配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3.  
  4. <servlet>
  5. <servlet-name>HelloCookieServlet</servlet-name>
  6. <servlet-class>com.hjh.cookie.HelloCookieServlet</servlet-class>
  7. </servlet>
  8. <servlet-mapping>
  9. <servlet-name>HelloCookieServlet</servlet-name>
  10. <url-pattern>/hello</url-pattern>
  11. </servlet-mapping>
  12.  
  13. </web-app>

  

  1. HelloCookieServlet.java源码
  1. package com.hjh.cookie;
  2.  
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.Cookie;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9.  
  10. /**
  11. * cookie入门
  12. */
  13. public class HelloCookieServlet extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15.  
  16. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  17. //设置编码:
  18. response.setContentType("text/html;charset=utf-8");
  19.  
  20. //创建一个cookie
  21. Cookie c1= new Cookie("user1","hjh");
  22.  
  23. //通过response写回到浏览器中
  24. response.addCookie(c1);
  25.  
  26. //提示信息
  27. response.getWriter().print("cookie已经写回");
  28. }
  29.  
  30. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  31. doGet(request, response);
  32. }
  33. }

  启动项目,第一次发送请求,在firefox浏览器中按f12键查看cookie,request中是没有cookie的,但是response中有cookie信息,如下图:

  第二次发送请求,再次查看cookie信息,request和response中都有cookie,且是同一个cookie,如下图:

  

  扩展-创建多个cookie:在前一个案例基础上,替换以下代码即可,

  1. //创建多个cookie
  2. Cookie c1= new Cookie("user1","hjh");
  3. Cookie c2= new Cookie("user2","sss");
  4. Cookie c3= new Cookie("user3","qqq");
  5.  
  6. //通过response写回到浏览器中
  7. response.addCookie(c1);
  8. response.addCookie(c2);
  9. response.addCookie(c3);

  启动项目,第一次发送请求,在firefox浏览器中按f12键查看cookie,request中是没有cookie的,但是response中有cookie信息,如下图:

  第二次发送请求,再次查看cookie信息,request和response中都有cookie,且是同一个cookie,如下图:

  案例:

  1. 案例1-步骤分析:
  2. 1.创建一个serlvet RemServlet 路径:/rem
  3. 2.servlet中:
  4. 获取指定cookie 例如:名称为 lastTime
  5. request.getCookies()
  6. 判断cookie是否为空
  7. 若为空:提示信息 第一次访问
  8. 若不为空:
  9. 获取此cookievalue
  10. 展示信息:你上次访问时间是....
  11.  
  12. 将这次访问时间记录,写会浏览器

  web.xml配置:

  1. <servlet>
  2. <servlet-name>RemServlet</servlet-name>
  3. <servlet-class>com.hjh.cookie.RemServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>RemServlet</servlet-name>
  7. <url-pattern>/rem</url-pattern>
  8. </servlet-mapping>
  1. RemServlet.java源码
  1. package com.hjh.cookie;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.Date;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.Cookie;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11.  
  12. /**
  13. * 记录上次访问时间
  14. */
  15. public class RemServlet extends HttpServlet {
  16. private static final long serialVersionUID = 1L;
  17.  
  18. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19. //设置编码
  20. response.setContentType("text/html;charset=utf-8");
  21. PrintWriter writer = response.getWriter();
  22.  
  23. //1.获取指定名称的cookie;request.getCookies()获取的为步骤3时创建的cookie
  24. Cookie c = getCookieByName("lastTime",request.getCookies());
  25.  
  26. //2.判断cookie是否为空
  27. if(c==null) {
  28. //cookie为空(第一次访问),提示 欢迎新用户访问本系统
  29. writer.print("欢迎新用户访问本系统");
  30. }else {
  31. //cookie不为空(第二次及之后访问),获取value,展示上一次访问的时间
  32. String value = c.getValue();
  33. long time = Long.parseLong(value);
  34. Date date = new Date(time);
  35. writer.print("您上次访问时间为:"+date.toLocaleString());
  36. }
  37.  
  38. //持久化cookie
  39. if(c!=null) {
  40. c.setMaxAge(3600);
  41. //设置路径
  42. c.setPath(request.getContentType()+"/");
  43. }
  44.  
  45. /*3.将当前访问时间记录写回浏览器(第一次访问,创建cookie;
  46. 第2次及以后的访问,都是将c指向更新了时间之后的cookie)*/
  47. c = new Cookie("lastTime",new Date().getTime()+"");
  48. response.addCookie(c);
  49. }
  50.  
  51. private Cookie getCookieByName(String name, Cookie[] cookies) {
  52. if(cookies!=null) {
  53. for (Cookie cookie : cookies) {
  54. if(name.equals(cookie.getName())) {
  55. return cookie;
  56. }
  57. }
  58. }
  59. return null;
  60. }
  61. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  62. doGet(request, response);
  63. }
  64. }

  第一次访问,页面显示如下:

  刷新页面再次访问,页面显示上次访问该项目的时间,页面显示如下:

  1. cookie-总结:
  2. 常用方法:
  3. setMaxAge(int 秒):设置cookie在浏览器端存活时间 以秒为单位
  4. 若设置成 0:删除该cookie(前提必须路径一致)
  5. setPath(String path):设置cookie的路径.
  6. 当我们访问的路径中包含此cookiepath,则携带
  7. 默认路径:
  8. 访问serlvet的路径,从"/项目名称"开始,到最后一个"/"结束
  9. 例如:
  10. 访问的serlvet路径:
  11. /day11/a/b/hello
  12. 默认路径为:
  13. /day11/a/b
  14. 手动设置路径:以"/项目名"开始,以"/"结尾;

案例2:记录用户浏览历史

  1. 需求:
  2. 当用户访问一个商品的时候,需要将该商品保留在浏览记录中
  3. 技术分析:
  4. cookie
  1. 步骤分析:
  2. 1.先将product_list.htm转成jsp
  3. 2.点击一个商品,展示该商品的信息,将该商品id记录到cookie (GetProductById)
  4. 获取之前的浏览记录 例如名称:ids
  5. 判断cookie是否为空
  6. 若为空 将当前商品的id起个名称 ids 放入cookie ids=1
  7. 若不为空,获取cookie当前值 例如:ids=2-1;使用"-"分割商品id
  8. 若当前访问的id=1 ,判断之前记录中有无该商品
  9. 若有:
  10. 将当前的id放入前面 结果 ids=1-2
  11. 若没有:
  12. 继续判断长度是否>=3
  13. 若>=3,移除最后一个,将当前的id放入最前面
  14. 若<3,直接将当前的id放入最前面.
  15.  
  16. ids=3-2-1 现在访问1 结果 ids=1-3-2
  17. ids=4-3-2 现在访问1 结果 ids=1-4-3
  18.  
  19. 3.再次回到product_list.jsp页面,需要将之前访问商品展示在浏览记录中
  20. 获取ids 例如:ids=2-3-1
  21. 切割

  web.xml配置:

  1. <servlet>
  2. <servlet-name>GetProductByIdServlet</servlet-name>
  3. <servlet-class>com.hjh.session.GetProductByIdServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>GetProductByIdServlet</servlet-name>
  7. <url-pattern>/getProductById</url-pattern>
  8. </servlet-mapping>
  1. GetProductByIdServlet.java源码:
  1. package com.hjh.session;
  2.  
  3. import java.io.IOException;
  4. import java.util.Arrays;
  5. import java.util.LinkedList;
  6. import java.util.List;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.Cookie;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import com.hjh.utils.CookieUtils;
  13.  
  14. public class GetProductByIdServlet extends HttpServlet {
  15. private static final long serialVersionUID = 1L;
  16.  
  17. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  18. //1.获取访问商品的id
  19. String id = request.getParameter("id");
  20.  
  21. //2.获取指定的cookie ids
  22. Cookie cookie = CookieUtils.getCookieByName("ids", request.getCookies());
  23.  
  24. //3.判断cookie是否存在
  25. String ids = "";
  26. if(cookie==null) {
  27. //cookie为空,需要将当前访问的商品id放入ids中
  28. ids = id;
  29. }else {
  30. //cookie不为空,继续判断当前访问商品id是否在ids中存在;ids以2-4-7形式存在
  31. //获取名为ids的cookie的值
  32. ids= cookie.getValue();
  33. //将ids进行切割,便于比较当前访问商品id是否存在于ids中
  34. String[] arr = ids.split("-");
  35. //将数组转成集合,此list长度不可变
  36. List<String> asList = Arrays.asList(arr);
  37. //将asList放入一个新的list集合中
  38. LinkedList<String> list = new LinkedList<>(asList);
  39.  
  40. //判断商品id是否存在ids中
  41. if(list.contains(id)){
  42. //若ids中包含id,将id移除,并在list最前面加上此id
  43. list.remove(id);
  44. list.addFirst(id);
  45. }else {
  46. //若ids中不存在id,继续判断长度是否大于2
  47. if(list.size()>2) {
  48. //长度>=3,移除最后一个,并将当前id放入list最前面
  49. list.removeLast();
  50. list.addFirst(id);
  51. }else{
  52. //长度<3,将当前id放入list最前面
  53. list.addFirst(id);
  54. }
  55. }
  56.  
  57. ids = "";
  58. //将list转成字符串(即ids)
  59. for(String s:list) {
  60. ids+=(s+"-");
  61. }
  62. ids=ids.substring(0, ids.length()-1);
  63. }//cookie不为空
  64.  
  65. //将ids写回去
  66. cookie = new Cookie("ids",ids);
  67. response.addCookie(cookie);
  68.  
  69. //设置访问路径
  70. cookie.setPath(request.getContextPath()+"/");
  71. //设置cookie存活时间
  72. cookie.setMaxAge(3600);
  73. //重定向跳转
  74. response.sendRedirect(request.getContextPath()+"/product_info"+id+".htm");
  75. }
  76.  
  77. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  78. doGet(request, response);
  79. }
  80. } 
  1. CookieUtils.java源码:
  1. package com.hjh.utils;
  2.  
  3. import javax.servlet.http.Cookie;
  4.  
  5. public class CookieUtils {
  6. public static Cookie getCookieByName(String name, Cookie[] cookies) {
  7. if(cookies!=null) {
  8. for (Cookie cookie : cookies) {
  9. if(name.equals(cookie.getName())) {
  10. return cookie;
  11. }
  12. }
  13. }
  14. return null;
  15. }
  16. }

  product_list.jsp

  1. <%@page import="com.hjh.utils.CookieUtils"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3. pageEncoding="UTF-8"%>
  4. <!doctype html>
  5. <html>
  6.  
  7. <head>
  8. <meta charset="utf-8" />
  9. <meta name="viewport" content="width=device-width, initial-scale=1">
  10. <title>会员登录</title>
  11.  
  12. <style>
  13. body {
  14. margin-top: 20px;
  15. margin: 0 auto;
  16. width: 100%;
  17. }
  18. .carousel-inner .item img {
  19. width: 100%;
  20. height: 300px;
  21. }
  22. .row{
  23. height:280px;
  24. }
  25. .col-md-2{
  26. float:left;
  27. margin-right: 100px;
  28. margin-left:10px;
  29. margin-top:10px;
  30. }
  31.  
  32. </style>
  33. </head>
  34.  
  35. <body>
  36.  
  37. <div class="row" style="width:1210px;margin:0 auto;">
  38.  
  39. <div class="col-md-2">
  40. <a href="/CookieSession/getProductById?id=1">
  41. <img src="./img/cs10001.jpg" width="170" height="170" style="display: inline-block;">
  42. </a>
  43. <p><a href="/CookieSession/getProductById?id=1" style='color:green'>衣服</a></p>
  44. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  45. </div>
  46.  
  47. <div class="col-md-2">
  48. <a href="/CookieSession/getProductById?id=2">
  49. <img src="img/cs10002.jpg" width="170" height="170" style="display: inline-block;">
  50. </a>
  51. <p><a href="/CookieSession/getProductById?id=2" style='color:green'>眼镜</a></p>
  52. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  53. </div>
  54.  
  55. <div class="col-md-2">
  56. <a href="/CookieSession/getProductById?id=3">
  57. <img src="img/cs10003.jpg" width="170" height="170" style="display: inline-block;">
  58. </a>
  59. <p><a href="/CookieSession/getProductById?id=3" style='color:green'></a></p>
  60. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  61. </div>
  62.  
  63. <div class="col-md-2">
  64. <a href="/CookieSession/getProductById?id=4">
  65. <img src="img/cs10004.jpg" width="170" height="170" style="display: inline-block;">
  66. </a>
  67. <p><a href="/CookieSession/getProductById?id=4" style='color:green'>手机</a></p>
  68. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  69. </div>
  70.  
  71. </div>
  72.  
  73. <!--
  74. 商品浏览记录:
  75. -->
  76. <div style="width:1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
  77. <h4 style="width: 50%;float: left;font: 14px/30px " 微软雅黑 ";">浏览记录<small>
                                       <a href="/CookieSession/clearHistory">清空</a></small></h4>
  78. <div style="width: 50%;float: right;text-align: right;"><a href="">more</a></div>
  79. <div style="clear: both;"></div>
  80. <div style="overflow: hidden;">
  81. <ul style="list-style: none;">
  82. <%
  83. //获取指定名称的cookie
  84.  
  85. Cookie cookie=CookieUtils.getCookieByName("ids", request.getCookies());
  86. //判断id是否为空
  87. if(cookie==null){
  88. %>
  89. <h2>暂无浏览记录</h2>
  90. <%
  91. }else{//ids=3-2-5
  92. String [] arr=cookie.getValue().split("-");
  93. for(String id:arr){
  94. %>
  95. <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>
  96. <%
  97. }
  98. }
  99. %>
  100. </ul>
  101. </div>
  102. </div>
  103. </body>
  104. </html>

  product_info1.htm:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>会员登录</title>
  7. <style>
  8. body {
  9. margin-top: 20px;
  10. margin: 0 auto;
  11. }
  12. .carousel-inner .item img {
  13. width: 100%;
  14. height: 300px;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="col-md-6">
  20. <div><strong>衣服</strong></div>
  21. <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
  22. <div>编号:751</div>
  23. </div>
  24. <div style="margin:10px 0 10px 0;">亿家价: <strong style="color:#ef0101;">¥:100元/件</strong>
                                                  参 考 价: <del>¥99.00元/件</del>
  25. </div>
  26. <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0;;background-color: #fffee6;">
  27. <div style="margin:5px 0 10px 0;">白色</div>
  28.  
  29. <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:
  30. <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
  31. <div style="margin:20px 0 10px 0;;text-align: center;">
  32. <a href="cart.htm">
  33. <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);
                                      height:36px;width:127px;" value="加入购物车" type="button">
  34. </a> &nbsp;收藏商品</div>
  35. </div>
  36. </div>
  37. <div class="clear"></div>
  38. <div style="width:950px;margin:0 auto;">
  39. <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
  40. <strong>商品介绍</strong>
  41. </div>
  42. <div>
  43. <img src="img/cs10001.jpg">
  44. </div>
  45. </div>
  46. </body>
  47. </html>

  product_info2.htm:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>会员登录</title>
  7. <style>
  8. body {
  9. margin-top: 20px;
  10. margin: 0 auto;
  11. }
  12. .carousel-inner .item img {
  13. width: 100%;
  14. height: 300px;
  15. }
  16. </style>
  17. </head>
  18.  
  19. <body>
  20. <div class="container">
  21. <div class="row">
  22. <div style="margin:0 auto;width:950px;">
  23. <div class="col-md-6">
  24. <div><strong>眼镜</strong></div>
  25. <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
  26. <div>编号:751</div>
  27. </div>
  28. <div style="margin:10px 0 10px 0;">亿家价: <strong style="color:#ef0101;">¥:200元/件</strong>
                                                  参 考 价: <del>¥199.00元/件</del>
  29. </div>
  30. <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                                    ;background-color: #fffee6;">
  31. <div style="margin:5px 0 10px 0;">白色</div>
  32. <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:
  33. <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
  34. <div style="margin:20px 0 10px 0;;text-align: center;">
  35. <a href="cart.htm">
  36. <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                              rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入购物车" type="button">
  37. </a> &nbsp;收藏商品</div>
  38. </div>
  39. </div>
  40. </div>
  41. <div class="clear"></div>
  42. <div style="width:950px;margin:0 auto;">
  43. <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
  44. <strong>商品介绍</strong>
  45. </div>
  46. <div>
  47. <img src="img/cs10002.jpg">
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </body>
  53. </html>

  product_info3.htm:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>会员登录</title>
  7. <style>
  8. body {
  9. margin-top: 20px;
  10. margin: 0 auto;
  11. }
  12. .carousel-inner .item img {
  13. width: 100%;
  14. height: 300px;
  15. }
  16. </style>
  17. </head>
  18.  
  19. <body>
  20. <div class="container">
  21. <div class="row">
  22. <div style="margin:0 auto;width:950px;">
  23. <div class="col-md-6">
  24. <div><strong></strong></div>
  25. <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
  26. <div>编号:751</div>
  27. </div>
  28. <div style="margin:10px 0 10px 0;">亿家价: <strong style="color:#ef0101;">¥:300元/份</strong>
                                                 参 考 价: <del>¥299.00元/份</del>
  29. </div>
  30. <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                                    ;background-color: #fffee6;">
  31. <div style="margin:5px 0 10px 0;">白色</div>
  32. <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:
  33. <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
  34. <div style="margin:20px 0 10px 0;;text-align: center;">
  35. <a href="cart.htm">
  36. <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                              rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入购物车" type="button">
  37. </a> &nbsp;收藏商品</div>
  38. </div>
  39. </div>
  40. </div>
  41. <div class="clear"></div>
  42. <div style="width:950px;margin:0 auto;">
  43. <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
  44. <strong>商品介绍</strong>
  45. </div>
  46. <div>
  47. <img src="img/cs10003.jpg">
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </body>
  53. </html>

  product_info4.htm:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>会员登录</title>
  7. <style>
  8. body {
  9. margin-top: 20px;
  10. margin: 0 auto;
  11. }
  12. .carousel-inner .item img {
  13. width: 100%;
  14. height: 300px;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="container">
  20. <div class="row">
  21. <div style="margin:0 auto;width:950px;">
  22.  
  23. <div class="col-md-6">
  24. <div><strong>手机</strong></div>
  25. <div style="border-bottom: 1px dotted #dddddd;width:350px;margin:10px 0 10px 0;">
  26. <div>编号:751</div>
  27. </div>
  28. <div style="margin:10px 0 10px 0;">亿家价: <strong style="color:#ef0101;">¥:400元/份</strong>
                                                  参 考 价: <del>¥388.00元/份</del>
  29. </div>
  30. <div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0
                                                  ;background-color: #fffee6;">
  31. <div style="margin:5px 0 10px 0;">白色</div>
  32. <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:
  33. <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
  34. <div style="margin:20px 0 10px 0;;text-align: center;">
  35. <a href="cart.htm">
  36. <input style="background: url('./images/product.gif') no-repeat scroll 0 -600px
                              rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入购物车" type="button">
  37. </a> &nbsp;收藏商品</div>
  38. </div>
  39. </div>
  40. </div>
  41. <div class="clear"></div>
  42. <div style="width:950px;margin:0 auto;">
  43. <div style="background-color:#d3d3d3;width:930px;padding:10px 10px;margin:10px 0 10px 0;">
  44. <strong>商品介绍</strong>
  45. </div>
  46. <div>
  47. <img src="img/cs10004.jpg" style="width:300px">
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </body>
  53. </html>

  启动项目,输入如下url,回车,在没有点击下面4张图片时,浏览记录为空,如下图:

  先点击眼镜这张图,然后点击包这张图,返回product_list.jsp页面,刷新,浏览记录显示如图:

扩展:删除浏览记录

  1. 技术分析:
  2. cookie.setMaxAge(0)
  1. 步骤分析:
  2. 1.在浏览器记录中添加一个超链接
  3. <a href="/day1101/clearHistroy">清空</a>
  4. 2.创建servlet clearHistroy
  5. 创建一个cookie
  6. 名称路径保持一致
  7. setMaxAge(0)
  8. 写回浏览器
  9. 3.页面跳转
  10. 重定向 product_list.jsp

  web.xml配置:

  1. <servlet>
  2. <servlet-name>ClearHistoryServlet</servlet-name>
  3. <servlet-class>com.hjh.session.ClearHistoryServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>ClearHistoryServlet</servlet-name>
  7. <url-pattern>/clearHistory</url-pattern>
  8. </servlet-mapping>
  1. ClearHistoryServlet.java源码:
  1. package com.hjh.session;
  2.  
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.Cookie;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9.  
  10. import com.hjh.utils.CookieUtils;
  11.  
  12. public class ClearHistoryServlet extends HttpServlet {
  13. private static final long serialVersionUID = 1L;
  14.  
  15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. //创建一个cookie
  17. Cookie cookie = CookieUtils.getCookieByName("ids", request.getCookies());
  18.  
  19. cookie.setPath(request.getContextPath()+"/");
  20.  
  21. //设置时间为0,即清空cookie
  22. cookie.setMaxAge(0);
  23.  
  24. //写回浏览器
  25. response.addCookie(cookie);
  26.  
  27. //页面跳转
  28. response.sendRedirect(request.getContextPath()+"/product_list.jsp");
  29. }
  30.  
  31. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  32. doGet(request, response);
  33. }
  34. }

   product_list.jsp:

  1. <%@page import="com.hjh.utils.CookieUtils"%>
  2. <%@ page language="java" contentType="text/html; charset=UTF-8"
  3. pageEncoding="UTF-8"%>
  4. <!doctype html>
  5. <html>
  6. <head>
  7. <meta charset="utf-8" />
  8. <meta name="viewport" content="width=device-width, initial-scale=1">
  9. <title>会员登录</title>
  10. <style>
  11. body {
  12. margin-top: 20px;
  13. margin: 0 auto;
  14. width: 100%;
  15. }
  16. .carousel-inner .item img {
  17. width: 100%;
  18. height: 300px;
  19. }
  20. .row{
  21. height:280px;
  22. }
  23. .col-md-2{
  24. float:left;
  25. margin-right: 100px;
  26. margin-left:10px;
  27. margin-top:10px;
  28. }
  29. </style>
  30. </head>
  31.  
  32. <body>
  33. <div class="row" style="width:1210px;margin:0 auto;">
  34. <div class="col-md-2">
  35. <a href="/CookieSession/getProductById?id=1">
  36. <img src="./img/cs10001.jpg" width="170" height="170" style="display: inline-block;">
  37. </a>
  38. <p><a href="/CookieSession/getProductById?id=1" style='color:green'>衣服</a></p>
  39. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  40. </div>
  41. <div class="col-md-2">
  42. <a href="/CookieSession/getProductById?id=2">
  43. <img src="img/cs10002.jpg" width="170" height="170" style="display: inline-block;">
  44. </a>
  45. <p><a href="/CookieSession/getProductById?id=2" style='color:green'>眼镜</a></p>
  46. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  47. </div>
  48.  
  49. <div class="col-md-2">
  50. <a href="/CookieSession/getProductById?id=3">
  51. <img src="img/cs10003.jpg" width="170" height="170" style="display: inline-block;">
  52. </a>
  53. <p><a href="/CookieSession/getProductById?id=3" style='color:green'></a></p>
  54. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  55. </div>
  56.  
  57. <div class="col-md-2">
  58. <a href="/CookieSession/getProductById?id=4">
  59. <img src="img/cs10004.jpg" width="170" height="170" style="display: inline-block;">
  60. </a>
  61. <p><a href="/CookieSession/getProductById?id=4" style='color:green'>手机</a></p>
  62. <p><font color="#FF0000">商城价:&yen;299.00</font></p>
  63. </div>
  64.  
  65. </div>
  66.  
  67. <!--
  68. 商品浏览记录:
  69. -->
  70. <div style="width:1210px;margin:0 auto; padding: 0 9px;border: 1px solid #ddd;border-top: 2px solid #999;height: 246px;">
  71. <h4 style="width: 50%;float: left;font: 14px/30px " 微软雅黑 ";">浏览记录<small>
                                  <a href="/CookieSession/clearHistory">清空</a></small></h4>
  72. <div style="width: 50%;float: right;text-align: right;"><a href="">more</a></div>
  73. <div style="clear: both;"></div>
  74. <div style="overflow: hidden;">
  75. <ul style="list-style: none;">
  76. <%
  77. //获取指定名称的cookie
  78. Cookie cookie=CookieUtils.getCookieByName("ids", request.getCookies());
  79. //判断id是否为空
  80. if(cookie==null){
  81. %>
  82. <h2>暂无浏览记录</h2>
  83. <%
  84. }else{//ids=3-2-5
  85. String [] arr=cookie.getValue().split("-");
  86. for(String id:arr){
  87. %>
  88. <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>
  89. <%
  90. }
  91. }
  92. %>
  93. </ul>
  94. </div>
  95. </div>
  96. </body>
  97. </html>

  启动项目,输入url,点击眼镜的图片,返回product_list.jsp页面,浏览记录里显示刚才的眼镜的记录,如下图:

  点击清空按钮,浏览记录中提示“暂无浏览记录”提示语,清空浏览记录在IE、firefox浏览器有效,在google浏览器中没有效果:

  1. 注意:
  2. cookie不能跨浏览器
  3. cookie中不支持中文

会话技术之cookie(记录当前时间、浏览记录的记录和清除)的更多相关文章

  1. 会话技术、Cookie技术与Session技术

    一.会话技术  1. 存储客户端状态 会话技术是帮助服务器记住客户端状态(区分客户端)的.  2. 会话技术 从打开一个浏览器访问某个站点,到关闭这个浏览器的整个过程,称为一次会话.会话技术就是记录这 ...

  2. Java第三阶段学习(十三、会话技术、Cookie技术与Session技术)

    一.会话技术  1. 存储客户端状态 会话技术是帮助服务器记住客户端状态(区分客户端)的.  2. 会话技术 从打开一个浏览器访问某个站点,到关闭这个浏览器的整个过程,称为一次会话.会话技术就是记录这 ...

  3. [转]【会话技术】Cookie技术

    建立时间:6.29 & 6.30 一.会话技术简介 1.存储客户端的状态 由一个问题引出今天的内容,例如网站的购物系统,用户将购买的商品信息存储到哪  里?因为Http协议是无状态的,也就是说 ...

  4. 会话技术之Cookie

    在无状态的客户端(未登录)下,张三想买手机然后把手机加入购物车,服务器发出添加成功的响应,然后把手机加入ServletContext域里,然后张三想在逛逛别的, 再无状态的客户端(未登录)下,李四想买 ...

  5. 会话技术( Cookie ,Session)

    会话技术:    会话:浏览器访问服务器端,发送多次请求,接受多次响应.直到有一方断开连接.会话结束.        解决问题:可以使用会话技术,在一次会话的多次请求之间共享数据.           ...

  6. JavaWeb学习之转发和重定向、会话技术:cookie、session、验证码实例、URLConnection使用(下载网页)(4)

    1.转发和重定向 HttpServletResponse response 转发: RequestDispatcher dispatcher = request.getRequestDispatche ...

  7. servlet会话技术:Cookie

    什么是会话会话可以简单理解为:用户开一个浏览器访问某个网站,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话.会话过程中需要解决的一些问题每个用户在使用浏览器与服务器进 ...

  8. Servlet第五篇【介绍会话技术、Cookie的API、详解、应用】

    什么是会话技术 基本概念: 指用户开一个浏览器,访问一个网站,只要不关闭该浏览器,不管该用户点击多少个超链接,访问多少资源,直到用户关闭浏览器,整个这个过程我们称为一次会话. 为什么我们要使用会话技术 ...

  9. Servle第四篇(会话技术之cookie)

    会话技术 什么是会话技术 基本概念: 指用户开一个浏览器,访问一个网站,只要不关闭该浏览器,不管该用户点击多少个超链接,访问多少资源,直到用户关闭浏览器,整个这个过程我们称为一次会话. 为什么我们要使 ...

随机推荐

  1. Luogu P3835 【模板】可持久化平衡树(fhq Treap)

    P3835 [模板]可持久化平衡树 题意 题目背景 本题为题目普通平衡树的可持久化加强版. 题目描述 您需要写一种数据结构(可参考题目标题),来维护一些数,其中需要提供以下操作(对于各个以往的历史版本 ...

  2. [转]C# 中的委托和事件 + 观察者模式

    引言 委托 和 事件在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易.它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去 ...

  3. Django项目:CRM(客户关系管理系统)--56--47PerfectCRM实现CRM客户报名流程01

    #urls.py """PerfectCRM URL Configuration The `urlpatterns` list routes URLs to views. ...

  4. sqlserver 创建用户 sp_addlogin

    创建新的 Microsoft® SQL Server™ 登录,使用户得以连接使用 SQL Server 身份验证的 SQL Server 实例.  语法: sp_addlogin [ @loginam ...

  5. redis学习笔记06-主从复制和哨兵机制

    1.主从复制 为了保证线上业务的持续运行,防止主节点因宕机而重启数据恢复消耗太长时间,通常会准备一个备用节点,备份主节点的数据,当主节点出问题时立马顶上.这种机制就叫做主从复制.在了解redis的主从 ...

  6. UOJ#422. 【集训队作业2018】小Z的礼物

    #422. [集训队作业2018]小Z的礼物 min-max容斥 转化为每个集合最早被染色的期望时间 如果有x个选择可以染色,那么期望时间就是((n-1)*m+(m-1)*n))/x 但是x会变,中途 ...

  7. 20190818 [ B ]-½

    请看到这个蒟蒻博客的人注意一下. 这是简单的[ B ]场考试,如果需要[ A ]场题解请去神犇们的blog. [ B ]场不需要题解,恩? 太蒟蒻了QAQ 考试过程: 怀着我是蒟蒻我怕谁的心情. 首先 ...

  8. hdu 1059 Dividing(多重背包优化)

    Dividing Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Su ...

  9. geoserver与OpenLayers配置

          geoserver与OpenLayers配置         目录   1     准备工作.... 4 1.1      需要用到的程序和资料... 4 2     地图格式转换方式(一 ...

  10. CI框架--URL路径跳转与传值

    CI框架使用URL的前提是需要加载辅助函数$this->load->helper('url');当然我建议大家将所有需要加载的东西写在构造方法内,这样就不需每个控制器每个方法都去调用一次了 ...