使用cookie技术实现,缓存最近浏览过详细信息的三本书的书名列表,并进行相应显示

(1)显示书名列表,及最近阅读的最多三本书的书名

public class ShowGoods extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 978235855242977508L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.write("所有的书籍是:");
		writer.write("</br>");
		for( Entry<String, MyBook> entry: OfferMap.getBookInfo().entrySet()){
			writer.write("<a href = '"+req.getContextPath()+"/ShowGoodsDetails?id="+entry.getKey()+"'>"+entry.getValue().getName()+"</a>");
			writer.write("</br>");
			
		}
		
		writer.write("最近浏览的三本书是:");
		writer.write("</br>");
		Cookie[] cookies = req.getCookies();
		if(cookies != null)
		for(Cookie cookie : cookies){
			if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
				String[] ids = cookie.getValue().split(",");
				for(String id : ids){
					writer.write("<a href = '"+req.getContextPath()+"/ShowGoodsDetails?id="+id+"'>"+OfferMap.getBookInfo().get(id).getName()+"</a>");
					writer.write("</br>");
				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

}

(2)显示书籍的详细信息,并将阅览的书名信息存到cookie中

public class ShowGoodsDetails extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -46163301904321918L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		LinkedHashMap<String, MyBook> map = OfferMap.getBookInfo();
		PrintWriter writer = resp.getWriter();
		String id = req.getParameter("id");
		if(id != null){
			MyBook myBook = map.get(id);
			writer.write(myBook.getName()+"的详细信息是:");
			writer.write("</br>");
			writer.print("ID是:"+myBook.getId()+"<br/>");
			writer.print("书本名是:"+myBook.getName()+"<br/>");
			writer.print("书本价格是:"+myBook.getPrice()+"<br/>");
		}
		
		LinkedList<String> list = new LinkedList<>();
		StringBuffer sb = new StringBuffer();
		Cookie[] cookies = req.getCookies();
		boolean flag = false;
		if(cookies != null){
			for(Cookie cookie : cookies){
				if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
					String[] ids = cookie.getValue().split(",");
					for(String idname : ids){
						list.add(idname);
					}
					
					//1、如果list中已经有3个,那么删除第一个,(存在一种情况,那就是原先已经有的三个里,这次又重复点击了,那么正常情况下,其位置应该需要变动)
					if(list.size() >= 3){
						list.removeFirst();
						list.addLast(id);
					}else {
						//2、如果list中不足3个,不是最后一个,那么就放在后边一个
						list.add(id);
					}
					for(String name : list){
						sb.append(name+",");
					}
					flag = true;
				}
				
			}
			
			if(flag){
				sb = sb.deleteCharAt(sb.length()-1);
				Cookie[] cookiess = req.getCookies();
				for(Cookie cookie : cookiess){
					if("lastVisitBook".equals(cookie.getName()) && cookie.getValue() != null){
						cookie.setValue(sb.toString());
					}
				}
				//putCookieToResp(resp,sb.toString());
			}else {
				putCookieToResp(resp,sb.append(id).toString());
			}
		}else {
			putCookieToResp(resp,sb.append(id).toString());
		}
		
	}

	private void putCookieToResp(HttpServletResponse resp, String string) {
		Cookie cookie = new Cookie("lastVisitBook", string);
		cookie.setMaxAge(3600*24*30);
		cookie.setPath("/webAndAjax");
		//cookie.setDomain("localhost");
		resp.addCookie(cookie);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

}

出现的问题:

一开始的时候,在原来有cookie的情况下,修改原来cookie内容的时候,使用的是new的方法,然后在显示时,一直只显示初始cookie的key值对应的内容。

       经过查询资料,  Cookie不仅仅有名字和值两个属性,还有域(domain),过期时间(expires),路径(path)等属性。其中,不同的域、不同的路径下可以存在同样名字的cookie。可以推测,相同路径和域下不能存在两个相同key值的cookie,所以,new两次,系统在获取的时候,第二次new的会出现错乱,而导致不能获取正确的cookie内容。

解决方法:采用 cookie 值修改的方式。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常抱歉,我是一个语言模型,无法真正地运行和实现功能。不过,我可以给您一些思路和指导。 1. 使用Session技术模拟购物车功能 在使用Session技术实现购物车功能时,我们可以将用户在购物车中添加的商品存储在Session中。首先,我们需要在用户添加商品到购物车时,将商品信息存储在Session中,例如: ```java // 获取Session对象 HttpSession session = request.getSession(); // 获取购物车中的商品列表 List<Item> cartItems = (List<Item>) session.getAttribute("cartItems"); // 如果购物车为空,则新建一个购物车列表 if (cartItems == null) { cartItems = new ArrayList<Item>(); } // 将新添加的商品加入购物车 cartItems.add(new Item(product, quantity)); // 更新购物车列表 session.setAttribute("cartItems", cartItems); ``` 在用户需要查看购物车中商品时,我们可以从Session中获取购物车列表,例如: ```java // 获取Session对象 HttpSession session = request.getSession(); // 获取购物车中的商品列表 List<Item> cartItems = (List<Item>) session.getAttribute("cartItems"); // 显示购物车中的商品列表 for (Item item : cartItems) { System.out.println(item.getProduct().getName() + " x " + item.getQuantity()); } ``` 2. 使用Cookie技术统计最近浏览过的5件商品信息使用Cookie技术统计最近浏览过的5件商品信息时,我们可以将每个商品的ID存储在Cookie中,然后在用户访问网站时,从Cookie中获取最近浏览过的5件商品的ID,再查询商品信息进行展示。例如: ```java // 获取最近浏览过的商品列表 List<Product> recentlyViewedProducts = new ArrayList<Product>(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("recentlyViewed")) { String[] productIds = cookie.getValue().split(","); for (String productId : productIds) { Product product = productService.getProductById(productId); if (product != null) { recentlyViewedProducts.add(product); } } break; } } } // 在访问商品详情页面时,将商品ID添加到CookieCookie recentlyViewedCookie = null; String recentlyViewed = ""; for (Product product : recentlyViewedProducts) { recentlyViewed += product.getId() + ","; } recentlyViewed += productId; recentlyViewedCookie = new Cookie("recentlyViewed", recentlyViewed); recentlyViewedCookie.setMaxAge(3600 * 24 * 30); response.addCookie(recentlyViewedCookie); ``` 在展示最近浏览过的商品时,我们可以从最近浏览过的商品列表中获取最近浏览过的5件商品进行展示,例如: ```java // 显示最近浏览过的5件商品 for (int i = recentlyViewedProducts.size() - 1; i >= Math.max(0, recentlyViewedProducts.size() - 5); i--) { Product product = recentlyViewedProducts.get(i); System.out.println(product.getName()); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值