商品浏览记录功能的实现

1.首先,商品列表页面部分代码如下:


    
        ${p.productId}
          ${p.productName}
        
        ${p.baseprice}
        ${p.store}
        
            
    

2.如上所示,点击商品名字可以查看商品详细信息,只要一查看信息就将商品ID以类似2-1-3的字符串存进名为pids的Cookie,并且最近查看的放在最前面,代码如下:

@RequestMapping("/productDetail")
public String productDetail(int productId, HttpServletRequest request, HttpServletResponse response, Model model){
    EcProduct ecProduct = ecProductService.selectByPrimaryKey(productId);
    
    String productid = productId+"";
    String pids = productid;
    Cookie[] cookies = request.getCookies();
    if(cookies.length!=0){
        for (Cookie cookie:cookies) {
            if("pids".equals(cookie.getName())){
                String[] split = cookie.getValue().split("-");
                List strings = Arrays.asList(split);
                LinkedList list=new LinkedList<>(strings);
                if(list.contains(productid)){
                    list.remove(productid);
                    list.addFirst(productid);
                }else {
                    list.addFirst(productid);
                }
                //将集合【2,1,3】转成字符串2-1-3
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < list.size()&&i<5; i++) {
                    stringBuilder.append(list.get(i));
                    stringBuilder.append("-");
                }
                 pids = stringBuilder.toString();
            }
        }
    }
    //将pid写到客户端的cookie
    Cookie cookie_pids=new Cookie("pids",pids);
    response.addCookie(cookie_pids);

    model.addAttribute("ecProduct",ecProduct);
    return "productDetail";
}

3.查看完详细信息,若返回商品列表页面,客户端则携带Cookie,将key为pids的Cookie里面的value取出,还原(如:2-1-3还原为[2,1,3]),并按顺序从数据库查商品信息。代码如下:

@RequestMapping("/index")
public String index(HttpServletRequest request,Model model) {
    EcProductExample example = new EcProductExample();
    example.createCriteria().andProductIdIsNotNull();
    List products = produceService.list(example);
    //定义一个记录历史浏览记录商品的集合
    List historyProductList=new ArrayList();
    int[] pids = new int[5];
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie:cookies) {
        if ("pids".equals(cookie.getName())) {
            String[] split = cookie.getValue().split("-");
            for (int i = 0; i < split.length&&i<5; i++) {
                pids[i] = Integer.parseInt(split[i]);
                EcProduct ecProduct = ecProductService.selectByPrimaryKey(pids[i]);
                historyProductList.add(ecProduct);
            }
        }
    }
    model.addAttribute("historyProductList",historyProductList);
    model.addAttribute("products", products);
    return "index";
}

4.浏览记录页面部分代码如下:



      ${history.productName}
    
    ${history.baseprice}


注意:本项目的浏览记录在商品列表的下方,在同一个页面index.jsp。

你可能感兴趣的:(商品浏览记录功能的实现)