Cookie小案例-----记住浏览过的商品记录
Cookie小案例------记住浏览过的商品记录
我们知道,这个功能在电商项目中非经常见。这里处理请求和页面显示都是由servlet实现,主要是为了体现cookie的作用,
实现功能例如以下:
1,点击购买的商品后,显示到还有一页面
2。记住用户浏览过的商品,并在页面时中显示
3,当浏览过的数量超过最大值限度时,最以下一个商品被挤下去
4,当浏览过的商品本身就在浏览记录中,显示列表将其从中间移到最上面
显示一打开站点的样子和显示用户的浏览记录:
package cn.itcast.cookie; import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//站点首页
public class CookieDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); //1.显示站点全部商品
out.print("本站点有例如以下书籍:<br/>");
Map<String,Book> map = DB.getMap();
for(Map.Entry<String, Book> entry : map.entrySet()){
Book book = entry.getValue();
out.print("<a href='/day07/servlet/CookieDemo3? id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
} out.print("您以前看过例如以下商品:<br/>");
//2.显示用户以前浏览过的商品 // bookHistory
Cookie cookie = null;
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
cookie = cookies[i];
}
}
if(cookie!=null){
//找到了bookHistory这个cookie
String bookHistory = cookie.getValue(); //4_6_1
String ids[] = bookHistory.split("\\_");
for(String id: ids){
Book book = (Book) DB.getMap().get(id);
out.print(book.getName() + "<br/>");
}
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} } class DB{
private static Map<String,Book> map = new HashMap();
static{
map.put("1", new Book("1","javaweb开发","老张"));
map.put("2", new Book("2","jdbc开发","老黎"));
map.put("3", new Book("3","struts2开发","老张"));
map.put("4", new Book("4","spring开发","老黎"));
map.put("5", new Book("5","hibernate开发","老张"));
} public static Map getMap(){
return map;
} } class Book{
private String id;
private String name;
private String author; public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(String id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
用于显示商品的具体信息:
package cn.itcast.cookie; import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//显示商品具体信息
public class CookieDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter(); //1.依据用户带过来的id值,显示对应商品的信息
out.print("您想看的书的具体信息为:<br/>");
String id = request.getParameter("id");
Book book = (Book) DB.getMap().get(id);
out.print(book.getId() + "<br/>");
out.print(book.getName() + "<br/>");
out.print(book.getAuthor() + "<br/>"); //2.以cookie的形式回写该商品的id号给浏览器
String bookHistory = makeCookie(book.getId(),request);
Cookie cookie = new Cookie("bookHistory",bookHistory);
cookie.setMaxAge(10000);
response.addCookie(cookie); } //依据用户原来看过的书,以及如今看的书的id,构建新的cookie值
private String makeCookie(String id, HttpServletRequest request) { //bookHistory=null 3 bookHistory=3
//bookHistory=2_1_5 3 bookHistory=3_2_1
//bookHistory=2 3 bookHistory=3_2
//bookHistory=2_3 3 bookHistory=3_2 //1.得到用户以前看过的书
String bookHistory = null;
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
bookHistory = cookies[i].getValue();
}
} if(bookHistory==null){
bookHistory = id;
return bookHistory;
} //bookHistory=1_2_5 代表用户以前看一些书。接着程序要得到用户以前看过什么书
String ids[] = bookHistory.split("_");
//为了检測数组中是否包括当前id,我们应该把数据转成集合,而且还要转成链表结构的集合
LinkedList<String> idList = new LinkedList(Arrays.asList(ids));
/*if(idList.contains(id)){
//bookHistory=2_3 3 bookHistory=3_2
idList.remove(id);
idList.addFirst(id);
}else{
//bookHistory=2_1_5 3 bookHistory=3_2_1
if(idList.size()>=3){
idList.removeLast();
idList.addFirst(id);
}else{
//bookHistory=2 3 bookHistory=3_2
idList.addFirst(id);
}
}*/
if(idList.contains(id)){
idList.remove(id);
}else{
if(idList.size()>=3){
idList.removeLast();
}
}
idList.addFirst(id); StringBuffer sb = new StringBuffer();
for(String lid: idList){ //1_2_3_
sb.append(lid + "_");
} return sb.deleteCharAt(sb.length()-1).toString();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
执行效果:
Cookie小案例-----记住浏览过的商品记录的更多相关文章
- Session与Cookie的原理以及使用小案例>从零开始学JAVA系列
目录 Session与Cookie的原理以及使用小案例 Cookie和Session所解决的问题 Session与Cookie的原理 Cookie的原理 Cookie的失效时机 小提示 Session ...
- Vue小案例 之 商品管理------学习过滤器 使用过滤器处理日期的格式
代码学习过滤器 过滤器介绍:过滤模型数据,在数据显示前做预处理操作: 内置过滤器:在1.x中,Vue提供了内置过滤器,但是在2.x中已经完全废除: 解决办法: (1)使用第三方库来替代1.x中的内置过 ...
- 一个ssm综合小案例-商品订单管理----写在前面
学习了这么久,一直都是零零散散的,没有把知识串联起来综合运用一番 比如拦截器,全局异常处理,json 交互,RESTful 等,这些常见技术必须要掌握 接下来呢,我就打算通过这么一个综合案例把这段时间 ...
- cookie记住浏览位置
/*返回上次浏览位置*/ $(function () { var str = window.location.href; str = str.substring(str.lastIndexOf(&qu ...
- Session小案例-----简单购物车的使用
Session小案例-----简单购物车的使用 同上篇一样,这里的处理请求和页面显示相同用的都是servlet. 功能实现例如以下: 1,显示站点的全部商品 2.用户点击购买后,可以记住用户选择的商品 ...
- Session小案例------完成用户登录
Session小案例------完成用户登录 在项目开发中,用户登陆功能再平常只是啦,当用户完毕username和password校验后.进入主界面,须要在主界面中显示用户的信息,此时用ses ...
- Session & Cookie小知识~
Cookie 一个HTTP cookie的(也称为网络Cookie,互联网的cookie,浏览器cookie,或者干脆饼干)是一小块从发送的数据的网站用户的并存储在用户的计算机上的网页浏览器,而用户浏 ...
- WEB 小案例 -- 网上书城(四)
针对于这个小案例我们今天讲解结账操作,也是有关这个案例的最后一次博文,说实话这个案例的博文写的很糟糕,不知道该如何去表述自己的思路,所以内容有点水,其实说到底还是功力不够. 处理思路 点击结账,发送结 ...
- ASP入门(九)-Request对象小案例
我们将制作一个能够记住访问者姓名的页面,在这个小案例中,你将学会如何使用Request对象的Cookies.Form以及ServerVariables集合的值,还可以学习到如何使用Response对象 ...
随机推荐
- JS / jquery 实现页面 面板拖动 QQ网页版登陆页面拖动
参考:慕课网DOM实践探秘 http://www.imooc.com/learn/138 实现需求:点击页面头部,可以拖动面板.使用js原生和jquery 各实现一次. 可以学到:1.鼠标在当前页面的 ...
- 从1到整数n中1出现的次数
题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数.例如输入12,从1到12这些整数中包含1的数字有1,10,11和12共出现了5次. 不考虑时间效率的解法: int Numbe ...
- HDU 2647 Reward【反向拓扑排序】
Reward Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- HDU 多校1.7
Function Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total ...
- Floyd-弗洛伊德算法
今天,研究一下谁都能看懂的弗洛伊德算法. 首先,弗洛伊德算法是一种利用动态规划的思想寻找给定的加权图中多源点之间最短路径的算法. 这个算法需要一个用到一个二维数组啊a[][],而a[i][j]表示的就 ...
- 【Android】 HttpClient 发送REST请求
直接po代码吧,第一个是一个枚举类型的类,是四种rest http请求,get/post/put/delete: public enum HttpRequestMethod { HttpGet { @ ...
- Difference between [0-9], [[:digit:]] and \d
Yes, it is [[:digit:]] ~ [0-9] ~ \d (where ~ means aproximate).In most programming languages (where ...
- (转)解析json xml
JSON数据 {"videos":[{"id":1,"image":"resources/images/minion_01.png ...
- Codeforces 920 G List Of Integers
题目描述 Let's denote as L(x,p)L(x,p) an infinite sequence of integers yy such that gcd(p,y)=1gcd(p,y)=1 ...
- [Contest20180328]coin
转化一下,相当于从$0$跳到$M$,每一步跳跃距离为$v_i$中的某个,每次跳跃距离不大于上一次,统计方案数 用$f_{i,j,k}$表示跳到$i$,第一步跳$v_j$,最后一步跳$\geq v_k$ ...