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");
}