Ofbiz——java中用cookie保留5个最近浏览记录

24 篇文章 0 订阅

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();// 删除最后多余 的一个逗号
	}
	
	
		   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值