Cookie实现记录用户浏览记录

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		/*
		 *Cookie实现用户浏览记录
		 */
		
		String id = request.getParameter("id");
		System.out.println(id);
		//获取历史浏览记录 history
		Cookie[] cookies = request.getCookies();
		Cookie cookie = CookieUtils.findCookieByName(cookies, "history");
		
		//如果为null,新建一个Cookie,设置值,设置maxage,返回给客户端
		if(cookie == null){
			Cookie c = new Cookie("history",id);
			c.setMaxAge(60 * 60);
			response.addCookie(c);
		}else{
			//如果不为null,取出原来的值再拼接上刚取出的id,设置值,设置maxage,返回给客户端
			
			// 2#3#1 如果此时再次浏览 1 -->  1#2#3 
			String ids = cookie.getValue();
			
			String[] idsArr = ids.split("#");
			String newIds = "";
			boolean b = ArrayUtils.contains(idsArr, id);
			if(b){
				String[] newIdsArr = ArrayUtils.remove(idsArr, ArrayUtils.indexOf(idsArr, id));
				newIds = String.join("#", newIdsArr);
				newIds = String.join("#", id,newIds);
			}else{
				 newIds = String.join("#", id,ids);
			}
			cookie.setValue(newIds);
			cookie.setMaxAge(60 * 60);
			response.addCookie(cookie);
			
		}
		
		response.sendRedirect("product_info.htm");
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值