使用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里面的值,并用逗号把它切割成一个数组 ...
随机推荐
- Codeforces 1176A Divide it!
题目链接:http://codeforces.com/problemset/problem/1176/A 思路:贪心,对第二个操作进行俩次等于将n变成n/3,第三个操作同理,我们将n不断除以2,再除以 ...
- C++之运算符_算数运算符
运算符 **作用:**用于执行代码的运算 | **运算符类型** | **作用** || -------------- | -------------------------------------- ...
- selenium基础-跳过验证码
selenium基础-跳过验证码 一.方法 设置万能验证码或者屏蔽验证码(最常用的方法) 使用验证码识别工具识别验证码 通过selenium操作cookies 直接使用配置文件的webdriver 二 ...
- flink流的执行大致流程图
- 2018-8-10-VisualStduio-打断点调试和不打断点调试有什么区别
title author date CreateTime categories VisualStduio 打断点调试和不打断点调试有什么区别 lindexi 2018-08-10 19:16:52 + ...
- 通讯录查询(Profile Lookup)——freeCodeCamp
- ssl checker
ssl checker showThis server is vulnerable to the POODLE attack. If possible, disable SSL 3 t` POODLE ...
- 使用line-height垂直居中在安卓手机上效果不好
前端实现单行垂直居中用的最多的方法可能就是line-height了吧.该属性在pc端和ios手机上效果都很好,可到了安卓手机,有很大几率发生文字上移的现象 知乎有人分析了导致这一现象的原因,Andro ...
- [JZOJ1904] 【2010集训队出题】拯救Protoss的故乡
题目 题目大意 给你一个树形的网络,每条边从父亲流向儿子.根节点为原点,叶子节点流向汇点,容量为无穷大. 可以给一些边扩大容量,最多总共扩大\(m\)容量.每条边的容量有上限. 求扩大容量后最大的最大 ...
- day34 反射、面向对象内置方法:如__str__、面向对象的软件开发
Python之路,Day21 = 反射.面向对象内置方法:如__str__.面向对象的软件开发 几个内置查看的方法使用 .__base__ 查看类的继承结构.mro() 对象找属性的顺序存在里面 -- ...