该功能分为四个模块:

1. 获取所有商品并以链接的形式显示

 out.write("网站商品: <br/>");
Map<String, Book> books = Db.getAll();
for (Map.Entry<String, Book> me : books.entrySet()) {
String id = me.getKey();
Book book = me.getValue();
out.write("<a href='/test/servlet/CookieDemo3?id="+ id +"'>"+ book.getName() +"</a><br/>");
}

模拟数据库和用户实体

 // 模拟数据库
class Db { // 要求: 1有序 2查找 -> LinkedHashMap
private static Map<String, Book> map = new LinkedHashMap<String, Book>(); // 初始化map
static {
map.put("1", new Book("JavaWeb秘籍", 12.45));
map.put("2", new Book("Spring开发", 45.5));
map.put("3", new Book("SpringMVC开发", 82.45));
map.put("4", new Book("Mybatis开发", 75.5));
} public static Map<String, Book> getAll() {
return map;
}
} // 商品实体
class Book { private String name;
private double price; public Book(String name, double price) {
this.name = name;
this.price = price;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
}
}

2. 显示用户上次浏览过的商品

通过用户携带的cookie显示用户历史浏览记录

 out.write("<br/>上次浏览过的商品: <br/>");
Cookie[] cookies = req.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookhistory")) {
String bookhistoryValue = cookies[i].getValue(); // 1_4_3
String[] ids = bookhistoryValue.split("\\_"); // [1, 4, 3]
// 迭代浏览过的商品id
for (String id : ids) {
out.write(Db.getAll().get(id).getName() + "<br/>");
}
}
}

说明: 第一步和第二步可以做成同一个servlet中, 完整代码:

 /**
* Created by IntelliJ IDEA.
*
* @Auther: ShaoHsiung
* @Date: 2018/8/28 10:12
* @Title: 显示用户上次浏览商品
* @Description: 主页
*/
public class CookieDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设置浏览器编码
resp.setContentType("text/html; charset=utf-8"); Writer out = resp.getWriter(); // 获取所有商品并以链接的形式显示
out.write("网站商品: <br/>");
Map<String, Book> books = Db.getAll();
for (Map.Entry<String, Book> me : books.entrySet()) {
String id = me.getKey();
Book book = me.getValue();
out.write("<a href='/test/servlet/CookieDemo3?id="+ id +"'>"+ book.getName() +"</a><br/>");
} // 显示用户上次浏览过的商品
out.write("<br/>上次浏览过的商品: <br/>");
Cookie[] cookies = req.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookhistory")) {
String bookhistoryValue = cookies[i].getValue(); // 1_4_3
String[] ids = bookhistoryValue.split("\\_"); // [1, 4, 3]
// 迭代浏览过的商品id
for (String id : ids) {
out.write(Db.getAll().get(id).getName() + "<br/>");
}
}
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
} // 模拟数据库
class Db { // 要求: 1有序 2查找 -> LinkedHashMap
private static Map<String, Book> map = new LinkedHashMap<String, Book>(); // 初始化map
static {
map.put("1", new Book("JavaWeb秘籍", 12.45));
map.put("2", new Book("Spring开发", 45.5));
map.put("3", new Book("SpringMVC开发", 82.45));
map.put("4", new Book("Mybatis开发", 75.5));
} public static Map<String, Book> getAll() {
return map;
}
} // 商品实体
class Book { private String name;
private double price; public Book(String name, double price) {
this.name = name;
this.price = price;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
}
}

3. 显示商品详细信息

通过请求参数在数据库中查询商品

 out.write("商品详细信息: <br/>");
String id = req.getParameter("id");
Book book = Db.getAll().get(id);
out.write(book.getName() + "<br/>");
out.write(book.getPrice() + "<br/>");

4. 将商品的id添加到cookie中并返回给用户

这里使用makeCookie()方法封装商品历史记录cookie的制作, 这部分主要任务就是将cookie返回给浏览器

 String bookhistoryValue = makeCookie(req, id);
Cookie bookhistory = new Cookie("bookhistory", bookhistoryValue);
bookhistory.setMaxAge(3600);
bookhistory.setPath(this.getServletContext().getContextPath());
resp.addCookie(bookhistory);

5. 完成makeCookie()方法

使用字符串拼接的方式产生cookie的具体步骤, 特别需要注意四种可能获取到的cookie及其处理方式.

注意: 四种可能获取到的cookie:

获取到的cookie    查看商品   返回的cookie
null 1 1
1_2_3 4 4_1_2
1_2_3 2 2_1_3
1_2 4 1_2_4

 private String makeCookie(HttpServletRequest req, String id) {
String bookhistoryValue = null;
Cookie[] cookies = req.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookhistory")) {
bookhistoryValue = cookies[i].getValue();
}
} // null 1 1
if (bookhistoryValue == null) {
return id;
}
List l = Arrays.asList(bookhistoryValue.split("\\_"));
// 转化为链表方便操作, 提供addFirst和removeLast等方法
LinkedList<String> list = new LinkedList();
list.addAll(l);
if (list.contains(id)) {
// 1_2_3 2 2_1_3
list.remove(id);
list.addFirst(id);
} else {
// 1_2_3 4 4_1_2
if (list.size() == 3) {
list.removeLast();
list.addFirst(id);
} else {
// 1_2 4 1_2_4
list.addFirst(id);
}
}
StringBuffer buffer = new StringBuffer();
for (String newId : list) {
buffer.append(newId + "_"); // 1_5_3_
}
return buffer.deleteCharAt(buffer.length()-1).toString(); // 删除最后一个下划线
}

说明: 同理, 第三步和第四步可以做成同一个servlet中, 完整代码:

 /**
* Created by IntelliJ IDEA.
*
* @Auther: ShaoHsiung
* @Date: 2018/8/28 10:12
* @Title: 显示用户上次浏览商品
* @Description: 商品详细信息页面
*/
public class CookieDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; charset=utf-8"); Writer out = resp.getWriter(); // 显示商品详细信息
out.write("商品详细信息: <br/>");
String id = req.getParameter("id");
Book book = Db.getAll().get(id);
out.write(book.getName() + "<br/>");
out.write(book.getPrice() + "<br/>"); // 将商品的id添加到cookie中并返回给用户
String bookhistoryValue = makeCookie(req, id);
Cookie bookhistory = new Cookie("bookhistory", bookhistoryValue);
bookhistory.setMaxAge(3600);
bookhistory.setPath(this.getServletContext().getContextPath());
resp.addCookie(bookhistory);
} private String makeCookie(HttpServletRequest req, String id) { String bookhistoryValue = null; Cookie[] cookies = req.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookhistory")) {
bookhistoryValue = cookies[i].getValue();
}
} /*
重点: 四种情况 获取到的cookie 查看商品 返回的cookie
null 1 1
1_2_3 4 4_1_2
1_2_3 2 2_1_3
1_2 4 1_2_4
*/ // null 1 1
if (bookhistoryValue == null) {
return id;
} List l = Arrays.asList(bookhistoryValue.split("\\_"));
// 转化为链表方便操作, 提供addFirst和removeLast等方法
LinkedList<String> list = new LinkedList();
list.addAll(l);
if (list.contains(id)) {
// 1_2_3 2 2_1_3
list.remove(id);
list.addFirst(id);
} else {
// 1_2_3 4 4_1_2
if (list.size() == 3) {
list.removeLast();
list.addFirst(id);
} else {
// 1_2 4 1_2_4
list.addFirst(id);
}
} StringBuffer buffer = new StringBuffer();
for (String newId : list) {
buffer.append(newId + "_"); // 1_5_3_
} return buffer.deleteCharAt(buffer.length()-1).toString(); // 删除最后一个下划线
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

效果图:

使用Cookie实现用户商品历史浏览记录的更多相关文章

  1. Django之使用redis缓存session,历史浏览记录,首页数据实现性能优化

    Redis缓存session 配置Django缓存数据到redis中 # diango的缓存配置 CACHES = { "default": { "BACKEND&quo ...

  2. Redis添加历史浏览记录

    参考资料 http://redisdoc.com/index.html http://redis-py.readthedocs.io/en/latest/#indices-and-tables 1.什 ...

  3. 用JS中的cookie实现商品的浏览记录

    最近在做一个购物车效果,为了实现商品的浏览记录效果可是让我百般周折,避免以后忘记特写此随笔与大家共享,希望博友们看后有所收获. 第一步:在一个公用的js文件下getCookie(“liulan”),c ...

  4. destoon系统开发-最新利用浏览器的cookie 做历史浏览记录

      注意: 代码 放在要显示的为 (一般放在详情页),注意本教程不入库,直接利用浏览器的 cookie 缓存判断    <!--历史浏览记录 S--> <div class=&quo ...

  5. JS制作一个通用的商城版历史浏览记录

    正在开发一个b2c的国外商城,昨天做了一个历史浏览记录发出来跟大家分享一下. JS: //cookie相关函数 function getCookieVal(offset) {    var endst ...

  6. position:搜索框显示历史浏览记录

    absolute 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位. 元素的位置通过 "left", "top", "righ ...

  7. js操作Cookie,实现历史浏览记录

    /** * history_teacher.jsp中的js,最近浏览名师 * @version: 1.0 * @author: mingming */ $(function(){ getHistory ...

  8. 使用modle1(jsp+javabeans)及cookie技术实现商品展示和浏览记录

    步骤1:创建dbHelper工具类,该类主要用于获取数据库连接,采用单例模式. 步骤2:创建实体类商品类,商品表,在dao实现数据的封装处理. 步骤3:在jsp页面导入实体类,调用DAO的静态方案获取 ...

  9. php中如何实现网上商城用户历史浏览记录的代码

    /如是COOKIE 里面不为空,则往里面增加一个商品ID if (!empty($_COOKIE['SHOP']['history'])){ //取得COOKIE里面的值,并用逗号把它切割成一个数组 ...

随机推荐

  1. Matlab中的lambda表达式 f=@(x) x^2-2*x+1;

    Matlab中的lambda表达式 f=@(x) x^-*x+;

  2. POJ2406-Power Strings-KMP循环节/哈希循环节

    Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc&quo ...

  3. 大神给你分析HTTPS和HTTP的区别

    今天在做雅虎的时候,发现用第三方工具截取不到客户端与服务端的通讯,以前重来没碰到过这种情况,仔细看了看,它的url请求时基于https的,gg了下发现原来https协议和http有着很大的区别.总的来 ...

  4. 使用Pyppeteer进行gmail模拟登录

    import asyncio import time from pyppeteer import launch async def gmailLogin(username, password, url ...

  5. Hadoop搭建,上传文件时出现错误,没有到主机的路由

    解决方案:(1)从namenode主机ping其它slaves节点的主机名(注意是slaves节点的主机名),如果ping不通,原因可能是namenode节点的/etc/hosts 未配置主机名与IP ...

  6. Docker学习のDocker和虚拟机

    最初听到Docker,是作为虚拟机来宣传的,但是它本质不是虚拟机 一.虚拟机 虚拟机(Virtual Machine)指通过软件模拟的具有完整硬件系统功能的.运行在一个完全隔离环境中的完整计算机系统. ...

  7. JedisCluster获取key所在的节点

    JedisCluster获取key所在的节点 2019年11月9日17:34:55 准备 引入jedis的jar包,这个jar包里面包含了JedisCluster,可以用它来操作集群. <dep ...

  8. 8-5接口测试用例设计与编写2 rest-assured

    rest-assured 简约的接口测试DSL 支持xml json的结构化解析 支持xpath jsonpath gpath等多种解析方式 对Spring的支持比较前面 底层是httpclient ...

  9. csps模拟86异或,取石子,优化题解

    题面:https://www.cnblogs.com/Juve/articles/11736440.html 异或: 考试时只想出了暴力 我们可以对于二进制下每一位w,求出[l,r]中有几个数在这一位 ...

  10. requestAnimationFrame动画封装

    function Animator(duration, progress) { this.duration = duration; this.progress = progress; this.nex ...