RecentlyViewed.java
package org.ofbiz.product.catalog;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import javolution.util.FastList;
/**
* @return
* @author LiuCheng
* @date 2015年11月26日
* @description
* 通过Cookie获取商品Id,显示最近浏览的商品
*/
public class RecentlyViewed {
/*
*
*/
public static List<String> getproductlist(HttpServletRequest request,HttpServletResponse response){
//获取商品Id
String productId = request.getAttribute("productId").toString();
//判断Cookie存在,以及获得最终的Cookie
String cookieValue = buildCookie(productId,request);
//把Cookie回写给浏览器
Cookie cookie = new Cookie("historyproductId",cookieValue);
cookie.setMaxAge(30*24*60*60);
cookie.setPath("/");
response.addCookie(cookie);
List<String> productIds = FastList.newInstance();
productIds.add(cookieValue);
return productIds;
}
/*
* 读取Cookie,把读到的商品Id放在list中
*/
private static String buildCookie(String productId, HttpServletRequest request) {
String historyproductId = null;
//获得所有的Cookie
Cookie[] cookies = request.getCookies();
//判断第几个Cookie为最终的值
for (int i = 0; cookies != null && i < cookies.length; i++) {
if("historyproductId".equals(cookies[i].getName())){
historyproductId = cookies[i].getValue();
break;
}
}
if (historyproductId == null)
return productId;
LinkedList<String> list = new LinkedList<String>(Arrays.asList(historyproductId.split("\\,")));
if (list.contains(productId)) {
list.remove(productId);
} else {
if (list.size() >= 5) {
list.removeLast();
}
}
list.addFirst(productId);
StringBuffer sb = new StringBuffer();
for (String bid : list) {
sb.append(bid + ",");
}
return sb.deleteCharAt(sb.length() - 1).toString();// 删除最后多余 的一个逗号
}
}