最近很忙,之前答应朋友写个商品浏览历史的文章。
上面是我本人做过的一个真实商业商城的历史浏览功能
历史浏览的功能[cookie存储商品id]
1、限定显示个数比如为5个
2、最新浏览的产品置顶
3、如果浏览的商品已经存在cookie中,则删除存在的商品,并且将现在的商品置顶
4、如果商品个数已经是5个了,则去掉最后一个商品,将新商品置顶
为了满足以上功能 采用LinkedList可以灵活的处理以上的业务需求
public static string BuildHistory(string productId) { string history=string.Empty; HttpCookieCollection cookies=HttpContext.Current.Request.Cookies;//获取cookie集合 for(int i=0;cookies!=null&&i<cookies.Count;i++) { if(cookies[i].Name=="history") { history=HttpUtility.UrlDecode(cookies[i].Value); } } if(history==null) { return HttpUtility.UrlDecode(productId); } LinkedList<string> list=new LinkedList<string>(history.Split(',')); if(list.Contains(productId))//如果当前商品id已经存在cookie中 { list.Remove(productId); } else { if(list.Count>=5) { list.RemoveLast();//如果个数已经达到最大值,则删除最后一个 } } list.AddFirst(productId);//最新的商品置顶 StringBuilder sb=new StringBuilder(); foreach(string proId in list) { sb.Append(proId+","); } return sb.ToString(0,sb.Length-1).ToString();//返回cookie值 }
构建history的cookie,调用以上的方法-->将当前的浏览的商品Id 这些就不写了