使用cookie模拟网站显示客户机上次访问的商品

       在该过程中需要创建两个Servlet,一个servlet中显示网站商品以及曾经浏览过的商品;一个servlet中根据商品ID号显示商品详细信息。图示如下:

构建显示网站商品的servlet代码如下:

//代表首页
public class CookieDemo2 extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解决乱码
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;chartset=UTF-8");
		
		PrintWriter out=response.getWriter();
		//1、列出网站所有商品
		out.print("本网站有如下商品:<br/>");
		Map<String,Book> map=Db.getAll();
		for (Map.Entry<String, Book> entry:map.entrySet()) {
			Book book=entry.getValue();
			out.print("<a href='/day07/CookieDemo3?id="+book.getId()+"'target='_blank'>"+book.getName()+"</a><br/>");
		}
		out.print("<br/><br/>");
		
		//2、显示用户曾经浏览过的商品(bookHistory=2_4_1)
		out.print("您曾经浏览过的商品:<br/>");
		Cookie [] cookies=request.getCookies();
		for (int i = 0;cookies!=null&& i < cookies.length; i++) {
			Cookie cookie=cookies[i];
			if(cookie.getName().equals("bookHistory")){
				String []ids=cookie.getValue().split("\\_");
				for (String id : ids) {
					Book book=(Book) Db.getAll().get(id);
					out.print((book.getName()+"<br/>"));
				}
			}
		}
          
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}



//使用类模拟数据库
class Db{
	//在创建集合时,若以后有检索数据的需求用Map,没有的话用List
	private static Map<String,Book> map=new LinkedHashMap();
	static{
		map.put("1", new Book("1","javaweb开发","老张",39));
		map.put("2", new Book("2","jdbc开发","老李",39));
		map.put("3", new Book("3","spring开发","老张",39));
		map.put("4", new Book("4","hiberanate开发","老方",39));
		map.put("5", new Book("5","ajax开发","老毕",39));
	}
	public static Map getAll(){
		return map;
	}
}
class Book{
	private String id;
	private String name;
	private String author;
	private double price;
	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 double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(String id, String name, String author, double price) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.price = price;
	}
	
}

根据商品id显示商品详细信息的servlet代码如下:

//显示商品详细信息
public class CookieDemo3 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//解决乱码
	response.setCharacterEncoding("UTF-8");
	response.setContentType("text/html;chartset=UTF-8");
    PrintWriter out=response.getWriter();
	
	//1、显示用户要查看的商品详细信息
	String id=request.getParameter("id");
	Book book=(Book) Db.getAll().get(id);
	out.print("您要看的书的详细信息为:<br/>");
	out.print("Id="+book.getId()+"<br/>");
	out.print("Name="+book.getName()+"<br/>");
	out.print("Author="+book.getAuthor()+"<br/>");
	out.print("Price="+book.getPrice()+"<br/>");
	
	
	
	
	
	//2、把用户看过的书的ID号以cookie形式回写给用户浏览器
	String bookHistory=buildBookHistory(request,id);
	Cookie cookie=new Cookie("bookHistory",bookHistory);
	cookie.setMaxAge(3600);
	cookie.setPath("/day07");
	response.addCookie(cookie);
	
	}
    //构建发送给浏览器的cookie的值
	private String buildBookHistory(HttpServletRequest request, String id) {
	
		//bookHistory    ""      1    bookHistory=1
		//bookHistory    3_1_5   1    bookHistory=1_3_5
		//bookHistory    3_2_5   1    bookHistory=1_3_2
		//bookHistory    5_2     1    bookHistory=1_5_2
		
		
		String bookHistory =null;
		Cookie[] cookies=request.getCookies();
		for (int i = 0;cookies!=null&& i < cookies.length; i++) {
			Cookie cookie =cookies[i];
			if(cookie.getName().equals("bookHistory")){
				bookHistory=cookie.getValue();
			}
		}
		//bookHistory    ""      1    bookHistory=1
		if(bookHistory==null){
			bookHistory=id;
			return bookHistory;
		}
		//bookHistory    3_1_5   1    bookHistory=1_3_5
		LinkedList<String> list=new LinkedList(Arrays.asList(bookHistory.split("\\_")));
		if(list.contains(id)){
			list.remove(id);
			list.addFirst(id);
		}else{
			//bookHistory    3_2_5   1    bookHistory=1_3_2
			if(list.size()>=3){
				list.removeLast();
				list.addFirst(id);
			}else{
				//bookHistory    5_2     1    bookHistory=1_5_2
				list.addFirst(id);
			}
		}
	StringBuffer sb=new StringBuffer();
	for (String str : list) {
		sb.append(str+"_");
	}
	//1_3_2_
	bookHistory=sb.deleteCharAt(sb.length()-1).toString();
	return bookHistory;
}
	protected 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、付费专栏及课程。

余额充值