1. 程式人生 > >商城系統PageBean分頁 Cookie儲存瀏覽記錄

商城系統PageBean分頁 Cookie儲存瀏覽記錄

封裝實體類:PageBean

public class PageBean<T> {
    private int currentPage;//當前頁
    private int currentCount;//頁面顯示條數
    private int totalCount;//總條數
    private int totalPage;//總頁數
    private List<T> list;//當前頁
}

 service分頁實現:

        ProductDao dao = new ProductDao();
        //封裝一個pageBean
PageBean<Product> pageBean = new PageBean<Product>(); //1.封裝當前頁 pageBean.setCurrentPage(currentPage); //2.封裝每頁顯示條數 pageBean.setCurrentCount(currentCount); //3.封裝總條數 int totalCount =0; try { totalCount = dao.getCount(cid); }
catch (SQLException e) { } pageBean.setTotalCount(totalCount); //4.封裝總頁數 int totalPage = (int) Math.ceil(1.0*totalCount/currentCount); pageBean.setTotalPage(totalPage); //5.封裝當前頁顯示的資料 int index= (currentPage-1)*currentCount;//起始索引 List<Product> list =null
; try { list = dao.findProductByPage(cid,index,currentCount); } catch (SQLException e) { e.printStackTrace(); } pageBean.setList(list); return pageBean;

 

productInfo  Servlet  開啟商品頁面,寫入cookie

//獲得客戶端攜帶cookie---獲得名字是pids的cookie
      
     String pid = request.getParameter("pid"); String pids = pid; Cookie[] cookies = request.getCookies(); if(cookies!=null){ for(Cookie cookie : cookies){ if("pids".equals(cookie.getName())){ pids = cookie.getValue(); //1-3-2 本次訪問商品pid是8----->8-1-3-2 //1-3-2 本次訪問商品pid是3----->3-1-2 //1-3-2 本次訪問商品pid是2----->2-1-3 //將pids拆成一個數組 String[] split = pids.split("-");//{3,1,2} List<String> asList = Arrays.asList(split); LinkedList<String> list = new LinkedList<String>(asList); //判斷集合中是否存在當前pid if(list.contains(pid)){ list.remove(pid); list.addFirst(pid); }else{ list.addFirst(pid); } //將[3,1,2]轉成3-1-2字串 StringBuffer sb = new StringBuffer(); for(int i = 0; i <list.size()&&i<7 ; i++){ sb.append(list.get(i)); sb.append("-"); } //去掉3-1-2-後的- pids = sb.substring(0, sb.length()-1); } } } Cookie cookie_pids = new Cookie("pids",pids); response.addCookie(cookie_pids); //轉發前,建立cookie儲存pid request.getRequestDispatcher("/product_info.jsp").forward(request, response);

 

productListBYCid  Servlet  開啟商品列表,讀取cookie

//定義一個記錄歷史商品資訊的集合
        List<Product> historyProductList = new ArrayList<Product>();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie cookie : cookies){
                if("pids".equals(cookie.getName())){
                    String pids = cookie.getValue();
                    String[] split = pids.split("-");
                    for(String pid : split){
                        Product product = service.findProductByPid(pid);
                        historyProductList.add(product);
                    }    
                }
            }
        }
        
        request.setAttribute("historyProductList", historyProductList);
        request.getRequestDispatcher("/product_list.jsp").forward(request, response);