在SESSION中保存值

一、基礎類

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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章