cookie案例之显示用户上次浏览过的商品

//网站首页
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.显示网站所有商品
		//print与write的区别在于有换行
		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
			//值为这样的:4_6_1
			String bookHistory = cookie.getValue(); 
			//以_分割字符串,需要转义
			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{
	//用map集合的原因为要用到检索数据的需求
	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开发","老张"));
	}
	//提供方法返回map集合
	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;
	}
}

//显示商品详细信息
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值(要求浏览历史只能保存3本书)
	private String makeCookie(String id, HttpServletRequest request) {
		//有以下四种情况
		//首次看id为3的书
		//bookHistory=null    3     bookHistory=3
		//浏览历史有三个了,但不包含id等于3的书,要删除最后一个再把3加在开头
		//bookHistory=2_1_5   3     bookHistory=3_2_1
		//浏览历史不超过3个,直接把3加在开头
		//bookHistory=2       3     bookHistory=3_2
		//浏览历史包含id为3的书,将其删除,再添加到开头
		//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    代表用户曾经看一些书,接着程序要得到用户曾经看过什么书
		//先切割成含有id的数组
		String ids[] = bookHistory.split("_");
		//为了检测数组中是否包含当前id,我们应该把数据转成集合,并且还要转成链表结构的集合,为了使用addFirst方法与removelast方法
		LinkedList<String> idList = new LinkedList(Arrays.asList(ids));
		//如果包含,就移除
		if(idList.contains(id)){
			idList.remove(id);
		}else{
			//如果不包含且长度够了,就删除最后一个
			if(idList.size()>=3){
				idList.removeLast();
			}
		}
		//总之都要在开头添加此id
		idList.addFirst(id);
		//再将id与_连接组合形成新的cookies的值,但末尾存在_
		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);
	}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值