需求分析:
ProductInfoServlet代码:
//获取到当前用户准备浏览的商品id String id = request.getParameter("id"); Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.fildCookie(cookies, "history"); //第一次浏览 if(cookie == null) { //响应返回Cookie Cookie c = new Cookie("history",id); c.setMaxAge(60*60); response.addCookie(c); }else { //第二次 //1、获取以前的Cookie,因为以前的Cookie,包含了浏览记录 String ids = cookie.getValue(); //2、让现在浏览的商品,和以前浏览的记录,形成Cookie的值 cookie.setValue(ids + "#" + id); cookie.setMaxAge(60*60); response.addCookie(cookie); } //跳转到具体页面 response.sendRedirect("product_info.htm");清除浏览记录的代码ClearHistory:
Cookie cookie = new Cookie("history", ""); cookie.setMaxAge(0);//设置立即删除 response.addCookie(cookie); response.sendRedirect("product_list.jsp");Cookie数组中找到具体目标Cookie代码片段是:
if(cookies !=null) { for (Cookie cookie : cookies) { if(name.equals(cookie.getName())) { return cookie; } } }product_list.jsp(商品列表页)中java代码片段:
<% Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.fildCookie(cookies,"history"); //如果Cookie是空,表明没有浏览任何商品 if(cookie == null){ %> <h2>没有浏览记录</h2> <% }else{ //不是空,表示有浏览记录 1#2#3 String[] ids = cookie.getValue().split("#"); for(String id : ids){ %> <li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;text-align: center;"><img src="products/1/cs1000<%=id %>.jpg" width="130px" height="130px" /></li> <% } } %> </ul> </div> <h2><a href="ClearHistory">清除浏览记录</a></h2>