关于用户浏览商品的历史记录(cookie)

该博客介绍了如何使用Cookie来记录用户浏览过的商品信息。首先创建了一个展示所有商品的界面,然后通过读取Cookie获取用户浏览历史并在页面上显示。同时,当用户查看某个商品详情时,会将该商品ID保存到Cookie中,限制历史记录数量并按浏览时间排序。最后,展示了如何构建和更新Cookie值的方法。
摘要由CSDN通过智能技术生成
创建对象:用集合模拟数据库:创建一个简单的内容显示界面
<pre name="code" class="java">package com.cn.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
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;

@SuppressWarnings("serial")
public class Cookie1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//1.创建所有商品信息
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset = UTF-8");
		PrintWriter out = response.getWriter();
		out.print("<center>");
		out.print("所有的商品信息:<br>");
		
		Map<String, Goods> map = Db.getAll();
		for(Map.Entry<String, Goods> entry:map.entrySet()){
			Goods goods = entry.getValue();
			out.print("<a href = '/Userinfo/Cookie2?id="+goods.getId()+"'targent = '_blank'>"+goods.getName()+"</a><br>");
		}
		
		out.print("</center>");
//2.显示用户曾经浏览过的商品
		out.print("你浏览过的商品为:<br>");
		Cookie cookies[] = request.getCookies();
		for(int i=0;cookies != null && i<cookies.length;i++){
			if(cookies[i].getName().equals("goodsHistory")){
				String ids[] = cookies[i].getValue().split("\\,");
				for(String id :ids){
					Goods goods = (Goods) Db.getAll().get(id);
					out.print("<a href = '/Userinfo/Cookie2?id="+goods.getId()+"'targent = '_blank'>"+goods.getName()+"</a><br/>");
				}
			}
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
			}

}
 class Db{
	private static Map<String , Goods> map = new LinkedHashMap();
	static {
		map.put("1",new Goods("1","红楼梦","曹雪芹","中国经典名著 "));
		map.put("2",new Goods("2","javaweb开发","白光元","javaweb自学书籍"));
		map.put("3",new Goods("3","西游记","吴承恩","中国经典名著"));
		map.put("4",new Goods("4","童年","高尔基","俄国经典名著"));
		map.put("5",new Goods("5","鲁滨逊漂流记","迪福","英国名著"));
		map.put("6",new Goods("6","java核心技术","马志强","java教科书"));
		map.put("7",new Goods("7","javaweb完全自学手册","宝柏","javaweb开发宝典"));
		map.put("8",new Goods("8","动态网站开发","萧萧","javaweb书籍"));
	}
	public static Map getAll(){
		return map;
	}
}
class Goods{
	private String id ;
	private String name;
	private String author;
	private String description;
	public Goods() {
		super();
		// TODO Auto-generated constructor stub
	}
	

	public Goods(String id, String name, String author, String description) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.description = description;
	}


	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 String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}


 
创建cookie;利用返回id显示商品的信息,并且保存在cookie的集合中:最后通过遍历的得到最近浏览的商品;
<pre name="code" class="java">package com.cn.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 Cookie2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//根据用户带来的id,显示商品的详细信息
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String id =request.getParameter("id");
		Goods goods = (Goods) Db.getAll().get(id);
		out.write(goods.getId()+"<br/>");
		out.write(goods.getName()+"<br/>");
		out.write(goods.getAuthor()+"<br/>");
		out.write(goods.getDescription()+"<br/>");
		
		
		
		
		
//构建cookie,回写给浏览器
		String cookieValue = buildCookie(id,request);
		Cookie cookie = new Cookie("goodsHistory",cookieValue);
		cookie.setMaxAge(1*30*24*3600);
		cookie.setPath("/Userinfo");
		response.addCookie(cookie);
		out.print("<a href = '/Userinfo/Cookie1'>返回首页</a>");
	}

	private String buildCookie(String id, HttpServletRequest request) {
		String goodsHistory = null;
		Cookie cookies[] =request.getCookies();
		for(int i = 0;cookies!=null&&i<cookies.length;i++){
			if(cookies[i].getName().equals("goodsHistory")){
				goodsHistory = cookies[i].getValue();
			}
		}
		if(goodsHistory ==null){
			return id;
		}
		LinkedList<String> list =new LinkedList(Arrays.asList(goodsHistory.split("\\,")));
		if(list.contains(id)){
			list.remove(id);
			list.addFirst(id);
		}else{
			if(list.size()>=3){
				list.removeLast();
				list.addFirst(id);
			}else{
				list.addFirst(id);
			}
		}
		
		
		StringBuilder sb =new StringBuilder();
		for(String bid:list){
			sb.append(bid+",");
		}
		return sb.deleteCharAt(sb.length()-1).toString();
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值