一、基础类
public class AuthCheckFilter implements Filter {
public void doFilter( ServletRequest arg0, ServletResponse arg1, FilterChain arg2 ) throws IOException, ServletException {
HttpServletRequest hrequest = (HttpServletRequest) arg0;
.......
//初始化历史浏览商品
Object o3 = hrequest.getSession().getAttribute("_HISTORY");
History history=null;
if(o3==null){
history=new History();
hrequest.getSession().setAttribute("_HISTORY", history);
}else{
history=(History) o3;
}
hrequest.setAttribute("history", history);
}
二、点击一个商品详情的时候调用此方法,讲商品添加到历史容器
public class ProductAction {
public ModelAndView detailView(HttpServletRequest request,
HttpServletResponse response) {
......
// 添加到历史浏览容器
History history = (History) request.getAttribute("history");
history.addHistory(pinfo);
// 取出历史浏览容器中的商品列表
List<Product> hps = history.getPlist();
request.setAttribute("hps", hps);
return new ModelAndView("/web/productDetail");
}
三、
/**
* 历史浏览容器,存放session来的历史浏览商品
* @author HXF
*
*/
package com.kuuwin.product.model;
import java.util.ArrayList;
import java.util.List;
public class History {
private List<Product> plist = new ArrayList<Product>();
public List<Product> getPlist() {
return plist;
}
public void setPlist(List<Product> plist) {
this.plist = plist;
}
/**
* 添加到历史浏览商品中
* @param p
*/
public void addHistory(Product p) {
//判断,如果已经有此商品,则不重复添加
boolean create = true;
long pid = p.getId();
List<Product> pList = this.getPlist();
for (Product l : pList) {
if (l.getId() == pid) {
create = false;
break;
}
}
//如果没有的商品,则添加,并且后添加的商品放在列表第一位
if (create) {
List<Product> newPlist=new ArrayList<Product>();
newPlist.add(p);
for (Product l : pList) {
newPlist.add(l);
}
this.plist.clear();
this.setPlist(newPlist);
}
}
}
四、页面中提取productDetail.vm
<div id="ad">
<div class="title"><h2>历史浏览</h2></div>
<div class="content">
<ul id="mycarousel" class="jcarousel jcarousel-skin-tango">
#foreach($h in $hps)
#set($img=$!h.bgetDefaultImage())
<li><a href="product.shtml?method=detailView&id=$!h.id" title="$!h.name"><img src="${contextPath}/$!img.bgetImgPath(1)" height="60px" width="60px" /></a></li>
#end
</ul>
</div>