使用Cookie实现用户商品历史浏览记录

时间:2022-05-13 02:45:22

该功能分为四个模块:

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实现用户商品历史浏览记录

使用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&plus;javabeans)及cookie技术实现商品展示和浏览记录

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

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

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

随机推荐

  1. HTML Select 标签选择后触发jQuery事件代码实例

    页面设计原由: 因为很多客户不知道如何来到我们公司,领导想让我在微信公众号上面做一个链接,客户可以直接通过微信公众号打开地图并导航到我们公司的办公地点. 实现起来并不难,但由于公司有很多办事处,所以需 ...

  2. CentOS6下基于Nginx搭建mp4&sol;flv流媒体服务器&lpar;可随意拖动&rpar;并支持RTMP&sol;HLS协议&lpar;含转码工具&rpar;

    1.先添加几个RPM下载源 1.1)安装RPMforge的CentOS6源     [root@AY130611215205Z ~]# wget -c http://pkgs.repoforge.or ...

  3. Python快速教程

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 怎么能快速地掌握Python?这是和朋友闲聊时谈起的问题. Python包含的内容 ...

  4. Appium移动自动化测试(四)--先跑起来再说(第一个测试用例-手机YY)

    说明 本文将详细说明如何使用Appnium完成:打开手机YY欢迎页面->按住屏幕向左滑动4次->按下"立即体验"按钮->按下"直播"按钮,的整 ...

  5. ionic goto other page or alert

    有时候需要 调试,这是就需要alert 的...可惜的是我不会angular  所以记录一下 .controller('mainctr', function($scope, $window) { $w ...

  6. Atom 插件安装

    “webstom” 目前还没免费版的 不过类似的倒是有个! 首先想到的一句话是:还在为webstom不是正版而发愁吗? 其实很小的时候我们的世界是非黑即白的,但慢慢长大后,发现其实还有灰色的存在! 工 ...

  7. unity中的mesh合并

    在分析shadowgun时,无意中发现所有的环境建筑运行后,都被合并成一个叫做 "Combined Mesha (root: scene)" 的mesh了,但是没有发现任何合并的脚 ...

  8. Servlet学习--练习示例总结

    醉了醉了..本来想测试下Servlet生命周期的,然后调了好久的错误,还是没成功,不知道为什么不能这样做 贴上代码: import java.io.IOException; import java.i ...

  9. HDU 4763 Theme Section&lpar;KMP灵活应用)

    Theme Section Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) To ...

  10. C&plus;&plus; STL中哈希表Map 与 hash&lowbar;map 介绍

    0 为什么需要hash_map 用过map吧?map提供一个很常用的功能,那就是提供key-value的存储和查找功能.例如,我要记录一个人名和相应的存储,而且随时增加,要快速查找和修改: 岳不群-华 ...