使用Cookie实现用户商品历史浏览记录
该功能分为四个模块:
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实现用户商品历史浏览记录的更多相关文章
- Django之使用redis缓存session,历史浏览记录,首页数据实现性能优化
Redis缓存session 配置Django缓存数据到redis中 # diango的缓存配置 CACHES = { "default": { "BACKEND&quo ...
- Redis添加历史浏览记录
参考资料 http://redisdoc.com/index.html http://redis-py.readthedocs.io/en/latest/#indices-and-tables 1.什 ...
- 用JS中的cookie实现商品的浏览记录
最近在做一个购物车效果,为了实现商品的浏览记录效果可是让我百般周折,避免以后忘记特写此随笔与大家共享,希望博友们看后有所收获. 第一步:在一个公用的js文件下getCookie(“liulan”),c ...
- destoon系统开发-最新利用浏览器的cookie 做历史浏览记录
注意: 代码 放在要显示的为 (一般放在详情页),注意本教程不入库,直接利用浏览器的 cookie 缓存判断 <!--历史浏览记录 S--> <div class=&quo ...
- JS制作一个通用的商城版历史浏览记录
正在开发一个b2c的国外商城,昨天做了一个历史浏览记录发出来跟大家分享一下. JS: //cookie相关函数 function getCookieVal(offset) { var endst ...
- position:搜索框显示历史浏览记录
absolute 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位. 元素的位置通过 "left", "top", "righ ...
- js操作Cookie,实现历史浏览记录
/** * history_teacher.jsp中的js,最近浏览名师 * @version: 1.0 * @author: mingming */ $(function(){ getHistory ...
- 使用modle1(jsp+javabeans)及cookie技术实现商品展示和浏览记录
步骤1:创建dbHelper工具类,该类主要用于获取数据库连接,采用单例模式. 步骤2:创建实体类商品类,商品表,在dao实现数据的封装处理. 步骤3:在jsp页面导入实体类,调用DAO的静态方案获取 ...
- php中如何实现网上商城用户历史浏览记录的代码
/如是COOKIE 里面不为空,则往里面增加一个商品ID if (!empty($_COOKIE['SHOP']['history'])){ //取得COOKIE里面的值,并用逗号把它切割成一个数组 ...
随机推荐
- APC注入DLL(win7下有问题)
void APCKernelRoutine(PKAPC pKAPC, PKNORMAL_ROUTINE pUserAPC, PVOID pContext, PVOID pSysArg1, PVOID ...
- RHEL / CentOS Linux Install Core Development Tools Automake, Gcc (C/C++), Perl, Python & Debuggers
how do I install all developer tools such as GNU GCC C/C++ compilers, make and others, after install ...
- chomp
用来除去最后的换行等空白字符. 例程: #!/usr/bin/perl #chomp.pl use warnings; use strict; print "Input a string & ...
- 20140412 iphone不完美越狱 无限黑屏解决
1.不完美越狱 工具:爱思助手.cydia 方法: 爱思助手刷6.1.3固件 一键越狱->关机越狱 高手工具->不完全越狱引导 进入手机后,打开cydia,下载insomnia防黑屏插件 ...
- 20140321 sizeof 虚函数与虚函数表 静态数组空间 动态数组空间 位字段
1.静态的数组空间char a[10];sizeof 不能用于1:函数类型 2:动态的数组空间new3:位字段 函数类型:int fun();sizeof(fun())计算的是返回类型的大小,并不是函 ...
- 字符串KMP算法
讲解:http://blog.csdn.net/starstar1992/article/details/54913261 #include <bits/stdc++.h> using n ...
- NEO4J中文分词全文索引自动更新解决方案
NEO4J中文分词全文索引自动更新解决方案 一.样例数据 二.英文与中文全文索引差别 1.创建NEO4J默认索引 2.删除索引 3.创建支持中文分词的索引 三.APOC自带英文全文索引过程(可自动更新 ...
- nio读取文件,输出文件
io流的一种: package com.cxy.ssp.Automic; import java.io.FileOutputStream; import java.io.IOException; im ...
- JS随机产生颜色
<script> function selectForm(lowerValue,upperValue){ var choices=upperValue-lowerValue+1; retu ...
- U Must Know The .Net --7
关键字 1 new 创建对象/调用构造函数 隐藏基类成员 new()约束,表明泛型类声明中的任何参数都必须有公共无参构造函数 new 实现多态 1.1 new class:分配内存,调用构造函数实例化 ...