该功能分为四个模块:

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. python数据结构之图的实现方法

    python数据结构之图的实现方法 本文实例讲述了python数据结构之图的实现方法.分享给大家供大家参考.具体如下: 下面简要的介绍下: 比如有这么一张图:     A -> B     A ...

  2. Cortex-M3的异常/中断屏蔽寄存器组

    转自 1. Cortex-M3的异常/中断屏蔽寄存器组 注:只有在特权级下,才允许访问这3个寄存器. 名 字 功能描述 PRIMASK 只有单一比特的寄存器.置为1后,就关掉所有可屏蔽异常,只剩下NM ...

  3. POJ 3761 Bubble Sort

    题目链接:https://vjudge.net/problem/POJ-3761 转自:https://blog.csdn.net/cscj2010/article/details/7820906 题 ...

  4. Deep Dive into Neo4j 3.5 Full Text Search

    In this blog we will go over the Full Text Search capabilities available in the latest major release ...

  5. MySQL 05章_模糊查询和聚合函数

    在之前的查询都需要对查询的关机中进行“精确”.“完整”完整的输入才能查询相应的结果, 但在实际开发过程中,通常需要考虑用户可能不知道“精确”.“完整”的关键字, 那么就需要提供一种不太严格的查询方式, ...

  6. BBS论坛 项目表分析

    一.项目表分析 from django.db import models from django.contrib.auth.models import AbstractUser # Create yo ...

  7. 修改jupyter保存文件目录

    参考: https://blog.csdn.net/lyxuefeng/article/details/79469189 步骤 打开 cmd 输入命令 jupyter notebook --gener ...

  8. note : Get FilePathName from FILE_OBJECT

    转自:http://blog.csdn.net/lostspeed/article/details/11738311 封了一个函数, 从 FILE_OBJECT 中 得到 FilePathName 在 ...

  9. bzoj1568 Blue Mary

    题意:P:加入一条一次函数.Q:询问x位置的最大函数值. 标程: #include<bits/stdc++.h> using namespace std; ; int q,x,n; dou ...

  10. java哈希表(线性探测哈希表。链式哈希表)

    哈希表(散列表) 通过哈希函数使元素的存储位置与它 的关键码之间能够建立一一映射的关系,在查找时可以很快找到该元素. 哈希表hash table(key,value) 的做法其实很简单,就是把Key通 ...