[項目構建 十一]babasport 購物車的原理及實現.


今天來開始寫一下關於購物車的東西, 這里首先拋出四個問題:

1)用戶沒登陸用戶名和密碼,添加商品, 關閉瀏覽器再打開后 不登錄用戶名和密碼 問:購物車商品還在嗎? 

2)用戶登陸了用戶名密碼,添加商品,關閉瀏覽器再打開后 不登錄用戶名和密碼 問:購物車商品還在嗎?   

3)用戶登陸了用戶名密碼,添加商品, 關閉瀏覽器,然后再打開,登陸用戶名和密碼  問:購物車商品還在嗎?

4)用戶登陸了用戶名密碼,添加商品, 關閉瀏覽器 外地老家打開瀏覽器  登陸用戶名和密碼 問:購物車商品還在嗎?

上面四個問題都是以京東為模板, 那么大家猜猜結果是什么呢?
1)在
2)不在了
3)在
4)在

如果你能夠猜到答案, 那么說明你真的很棒, 那么關於這四點是怎么實現的呢? (如果有不認可的小伙伴可以用京東實驗一下)
下面我們就來講解下購物車的原理,最后再來說下具體的code實現.
1)用戶沒有登錄, 添加商品, 此時的商品是被添加到了瀏覽器的Cookie中, 所以當再次訪問時(不登錄),商品仍然在Cookie中, 所以購物車中的商品還是存在的.
2)用戶登錄了,添加商品, 此時會將Cookie中和用戶選擇的商品都添加到購物車中, 然后刪除Cookie中的商品. 所以當用戶再次訪問(不登錄),此時Cookie中的購物車商品已經被刪除了, 所以此時購物車中的商品不在了.
3)用戶登錄, 添加商品,此時商品被添加到數據庫做了持久化存儲, 再次打開登錄用戶名和密碼, 該用戶選擇的商品肯定還是存在的, 所以購物車中的商品還是存在的.
4)理由3)


這里再說下 沒登錄 保存商品到Cookie的優點以及保存到Session和數據庫的對比:

1:Cookie: 優點: 保存用戶瀏覽器(不用浪費我們公司的服務器) 缺點:Cookie禁用,不提供保存
2:Session:(Redis : 浪費大量服務器內存:實現、禁用Cookie) 速度很快
3:數據庫(Mysql、Redis、SOlr) 能持久化的就數據庫 速度太慢

那么我今天要講的就是:

用戶沒登陸:購物車添加到Cookie中
用戶登陸: 保存購物車到Redis中 (不用數據庫)

整體的思路圖解:

接下來就是代碼實例來實現 購物車的功能了:

1,將商品加入購物車中

1 //加入購物車
2 function  addCart(){
3       //  + skuId
4       window.location.href="/shopping/buyerCart?skuId="+skuId+"&amount="+$("#buy-num").val();
5 }

這里傳入的參數是skuId(庫存表的主鍵, 庫存表保存的商品id,顏色,尺碼,庫存等信息), 購買數量amount.

接着我們來看Controller是如何來處理的:

//加入購物車
    @RequestMapping(value="/shopping/buyerCart")
    public <T> String buyerCart(Long skuId, Integer amount, HttpServletRequest request,
            HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException{
        //將對象轉換成json字符串/json字符串轉成對象
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(Include.NON_NULL);
        BuyerCart buyerCart = null;
        //1,獲取Cookie中的購物車
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //
                if (Constants.BUYER_CART.equals(cookie.getName())) {
                    //購物車 對象 與json字符串互轉
                    buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
                    break;
                }
            }
        }
        
        //2,Cookie中沒有購物車, 創建購物車對象
        if (null == buyerCart) {
            buyerCart = new BuyerCart();
        }
        
        //3, 將當前款商品追加到購物車
        if (null != skuId && null != amount) {
            Sku sku = new Sku();
            sku.setId(skuId);
            BuyerItem buyerItem = new BuyerItem();
            buyerItem.setSku(sku);
            //設置數量
            buyerItem.setAmount(amount);
            //添加購物項到購物車
            buyerCart.addItem(buyerItem);
        }
        
        //排序  倒序
        List<BuyerItem> items = buyerCart.getItems();
        Collections.sort(items, new Comparator<BuyerItem>() {

            @Override
            public int compare(BuyerItem o1, BuyerItem o2) {
                return -1;
            }
            
        });
        
        //前三點 登錄和非登錄做的是一樣的操作, 在第四點需要判斷
        String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
        if (null != username) {
            //登錄了
            //4, 將購物車追加到Redis中
            cartService.insertBuyerCartToRedis(buyerCart, username);
            //5, 清空Cookie 設置存活時間為0, 立馬銷毀
            Cookie cookie = new Cookie(Constants.BUYER_CART, null);
            cookie.setPath("/");
            cookie.setMaxAge(-0);
            response.addCookie(cookie);
        }else {
            //未登錄
            //4, 保存購物車到Cookie中
            //將對象轉換成json格式
            Writer w = new StringWriter();
            om.writeValue(w, buyerCart);
            Cookie cookie = new Cookie(Constants.BUYER_CART, w.toString());
            //設置path是可以共享cookie
            cookie.setPath("/");
            //設置Cookie過期時間: -1 表示關閉瀏覽器失效  0: 立即失效  >0: 單位是秒, 多少秒后失效
            cookie.setMaxAge(24*60*60);
            //5,Cookie寫會瀏覽器
            response.addCookie(cookie);
        }
        
        //6, 重定向
        return "redirect:/shopping/toCart";
    }

這里設計一個知識點: 將對象轉換成json字符串/json字符串轉成對象
我們在這里先寫一個小的Demo來演示json和對象之間的互轉, 這里使用到了springmvc中的ObjectMapper類.

public class TestJson {

    @Test
    public void testAdd() throws Exception {
        TestTb testTb = new TestTb();
        testTb.setName("范冰冰");
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(Include.NON_NULL);
        //將對象轉換成json字符串
        Writer wr = new StringWriter();
        om.writeValue(wr, testTb);
        System.out.println(wr.toString());
        
        //轉回對象
        TestTb r = om.readValue(wr.toString(), TestTb.class);
        System.out.println(r.toString());
    }
    
}

執行結果: 

這里我們使用了Include.NON_NULL, 如果TestTb 中屬性為null 的就不給轉換成Json, 從對象-->Json字符串  用的是objectMapper.writeValue(). 從Json字符串-->對象使用的是objectMapper.readValue().
回歸上面我們項目中的代碼, 只有未登錄 添加商品時才會將此商品添加到Cookie中.

//未登錄
            //4, 保存購物車到Cookie中
            //將對象轉換成json格式
            Writer w = new StringWriter();
            om.writeValue(w, buyerCart);
            Cookie cookie = new Cookie(Constants.BUYER_CART, w.toString());
            //設置path是可以共享cookie
            cookie.setPath("/");
            //設置Cookie過期時間: -1 表示關閉瀏覽器失效  0: 立即失效  >0: 單位是秒, 多少秒后失效
            cookie.setMaxAge(24*60*60);
            //5,Cookie寫會瀏覽器
            response.addCookie(cookie);

我們debug 可以看到:

這里已經將對象購物車對象buyerCart轉換成了Json格式.
將商品添加到購物車, 不管是登錄還是未登錄, 都要先取出Cookie中的購物車, 然后將當前選擇的商品追加到購物車中.
然后登錄的話  就把Cookie中的購物車清空, 並將購物車的內容添加到Redis中做持久化保存.
如果未登錄, 將選擇的商品追加到Cookie中.

將購物車追加到Redis中的代碼:insertBuyerCartToRedis(這里面包含了判斷添加的是否是同款)

//保存購物車到Redis中
    public void insertBuyerCartToRedis(BuyerCart buyerCart, String username){
        List<BuyerItem> items = buyerCart.getItems();
        if (items.size() > 0) {
            //redis中保存的是skuId 為key , amount 為value的Map集合
            Map<String, String> hash = new HashMap<String, String>();
            for (BuyerItem item : items) {
                //判斷是否有同款
                if (jedis.hexists("buyerCart:"+username, String.valueOf(item.getSku().getId()))) {
                    jedis.hincrBy("buyerCart:"+username, String.valueOf(item.getSku().getId()), item.getAmount());
                }else {
                    hash.put(String.valueOf(item.getSku().getId()), String.valueOf(item.getAmount()));
                }
            }
            if (hash.size() > 0) {
                jedis.hmset("buyerCart:"+username, hash);
            }
        }
        
    }

判斷用戶是否登錄: String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));

 

public class RequestUtils {

    //獲取CSessionID
    public static String getCSessionId(HttpServletRequest request, HttpServletResponse response){
        //1, 從Request中取Cookie
        Cookie[] cookies = request.getCookies();
        //2, 從Cookie數據中遍歷查找, 並取CSessionID
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("CSESSIONID".equals(cookie.getName())) {
                    //有, 直接返回
                    return cookie.getValue();
                }
            }
        }
        //沒有, 創建一個CSessionId, 並且放到Cookie再返回瀏覽器.返回新的CSessionID
        String csessionid = UUID.randomUUID().toString().replaceAll("-", "");
        //並且放到Cookie中
        Cookie cookie = new Cookie("CSESSIONID", csessionid);
        //cookie  每次都帶來, 設置路徑
        cookie.setPath("/");
        //0:關閉瀏覽器  銷毀cookie. 0:立即消失.  >0 存活時間,秒
        cookie.setMaxAge(-1);
        
        return csessionid;
    }
}
//獲取
    public String getAttributterForUsername(String jessionId){
        String value = jedis.get(jessionId + ":USER_NAME");
        if(null != value){
            //計算session過期時間是 用戶最后一次請求開始計時.
            jedis.expire(jessionId + ":USER_NAME", 60*exp);
            return value;
        }
        return null;
    }

sessionProviderService

==========================================2,購物車展示頁面
最后 重定向到購物車展示頁: return "redirect:/shopping/toCart"; 這里進入結算頁有兩種方式:
1) 在商品詳情頁 點擊加入購物車.
2) 直接點擊購物車按鈕 進入購物車結算頁.

下面來看下結算頁的代碼:

@Autowired
    private CartService cartService;
    //去購物車結算, 這里有兩個地方可以直達: 1,在商品詳情頁 中點擊加入購物車按鈕  2, 直接點擊購物車按鈕
    @RequestMapping(value="/shopping/toCart")
    public String toCart(Model model, HttpServletRequest request,
            HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException{ 
        //將對象轉換成json字符串/json字符串轉成對象
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(Include.NON_NULL);
        BuyerCart buyerCart = null;
        //1,獲取Cookie中的購物車
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //
                if (Constants.BUYER_CART.equals(cookie.getName())) {
                    //購物車 對象 與json字符串互轉
                    buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
                    break;
                }
            }
        }
        
        //判斷是否登錄
        String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
        if (null != username) {
            //登錄了
            //2, 購物車 有東西, 則將購物車的東西保存到Redis中
            if (null == buyerCart) {
                cartService.insertBuyerCartToRedis(buyerCart, username);
                //清空Cookie 設置存活時間為0, 立馬銷毀
                Cookie cookie = new Cookie(Constants.BUYER_CART, null);
                cookie.setPath("/");
                cookie.setMaxAge(-0);
                response.addCookie(cookie);
            }
            //3, 取出Redis中的購物車
            buyerCart = cartService.selectBuyerCartFromRedis(username);
        }
        
        
        //4, 沒有 則創建購物車
        if (null == buyerCart) {
            buyerCart = new BuyerCart();
        }
        
        //5, 將購物車裝滿, 前面只是將skuId裝進購物車, 這里還需要查出sku詳情
        List<BuyerItem> items = buyerCart.getItems();
        if(items.size() > 0){
            //只有購物車中有購物項, 才可以將sku相關信息加入到購物項中
            for (BuyerItem buyerItem : items) {
                buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));
            }
        }
        
        //5,上面已經將購物車裝滿了, 這里直接回顯頁面
        model.addAttribute("buyerCart", buyerCart);
        
        //跳轉購物頁面
        return "cart";
    }

這里 就是 購物車詳情展示頁面, 這里需要注意, 如果是同一件商品連續添加, 是需要合並的.
購物車詳情展示頁面就包括兩大塊, 1) 商品詳情 2)總結
其中1)商品詳情又包括 商品尺碼,商品顏色, 商品購買數量, 是否有貨.

取出Redis中的購物車: buyerCart = cartService.selectBuyerCartFromRedis(username);

//取出Redis中購物車
    public BuyerCart selectBuyerCartFromRedis(String username){
        BuyerCart buyerCart = new BuyerCart();
        //獲取所有商品, redis中保存的是skuId 為key , amount 為value的Map集合
        Map<String, String> hgetAll = jedis.hgetAll("buyerCart:"+username);
        Set<Entry<String, String>> entrySet = hgetAll.entrySet();
        for (Entry<String, String> entry : entrySet) {
            //entry.getKey(): skuId
            Sku sku = new Sku();
            sku.setId(Long.parseLong(entry.getKey()));
            BuyerItem buyerItem = new BuyerItem();
            buyerItem.setSku(sku);
            //entry.getValue(): amount
            buyerItem.setAmount(Integer.parseInt(entry.getValue()));
            //添加到購物車中
            buyerCart.addItem(buyerItem);
        }
        
        return buyerCart;
    }

將購物車裝滿, 前面只是將skuId裝進購物車, 這里還需要查出sku詳情: List<BuyerItem> items = buyerCart.getItems();
buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));

//向購物車中的購物項 添加相應的數據, 通過skuId 查詢sku對象, 顏色對象, 商品對象
    public Sku selectSkuById(Long skuId){
        Sku sku = skuDao.selectByPrimaryKey(skuId);
        //顏色
        sku.setColor(colorDao.selectByPrimaryKey(sku.getColorId()));
        //添加商品信息
        sku.setProduct(productDao.selectByPrimaryKey(sku.getProductId()));
        return sku;
    }

接着就返回"cart.jsp", 這個就是購物車詳情展示頁面了.

================================================3, 去結算頁面
到了這里就說明用戶必須要 登錄, 而且購物車中必須要有商品.
所以這里我么你需要利用springmvc的過濾功能, 用戶點擊結算的時候必須要先登錄, 如果沒有登錄的話就提示用戶需要登錄.

 

//去結算
    @RequestMapping(value="/buyer/trueBuy")
    public String trueBuy(String[] skuIds, Model model, HttpServletRequest request, HttpServletResponse response){
        //1, 購物車必須有商品, 
        //取出用戶名  再取出購物車
        String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
        //取出所有購物車
        BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds(skuIds, username);
        List<BuyerItem> items = buyerCart.getItems();
        if (items.size() > 0) {
            //購物車中有商品
            //判斷所勾選的商品是否都有貨, 如果有一件無貨, 那么就刷新頁面.
            Boolean flag = true;
            //2, 購物車中商品必須有庫存 且購買大於庫存數量時視為無貨. 提示: 購物車原頁面不動. 有貨改為無貨, 加紅提醒.
            for (BuyerItem buyerItem : items) {
                //裝滿購物車的購物項, 當前購物項只有skuId這一個東西, 我們還需要購物項的數量去判斷是否有貨
                buyerItem.setSku(cartService.selectSkuById(buyerItem.getSku().getId()));
                //校驗庫存
                if (buyerItem.getAmount() > buyerItem.getSku().getStock()) {
                    //無貨
                    buyerItem.setIsHave(false);
                    flag = false;
                }
                if (!flag) {
                    //無貨, 原頁面不動, 有貨改成無貨, 刷新頁面.
                    model.addAttribute("buyerCart", buyerCart);
                    return "cart";
                }
            }
        }else {
            //購物車沒有商品
            //沒有商品: 1>原購物車頁面刷新(購物車頁面提示沒有商品)
            return "redirect:/shopping/toCart";
        }
        
        
        //3, 正常進入下一個頁面
        return "order";
    }

取出 所指定的購物車, 因為我們結算之前在購物車詳情頁面會勾選 我們 需要購買的商品, 所以這里是根據所勾選的商品去結算的.
BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds(skuIds, username);
從購物車中取出指定商品:

//從購物車中取出指定商品
    public BuyerCart selectBuyerCartFromRedisBySkuIds(String[] skuIds, String username){
        BuyerCart buyerCart = new BuyerCart();
        //獲取所有商品, redis中保存的是skuId 為key , amount 為value的Map集合
        Map<String, String> hgetAll = jedis.hgetAll("buyerCart:"+username);
        if (null != hgetAll && hgetAll.size() > 0) {
            Set<Entry<String, String>> entrySet = hgetAll.entrySet();
            for (Entry<String, String> entry : entrySet) {
                for (String skuId : skuIds) {
                    if (skuId.equals(entry.getKey())) {
                        //entry.getKey(): skuId
                        Sku sku = new Sku();
                        sku.setId(Long.parseLong(entry.getKey()));
                        BuyerItem buyerItem = new BuyerItem();
                        buyerItem.setSku(sku);
                        //entry.getValue(): amount
                        buyerItem.setAmount(Integer.parseInt(entry.getValue()));
                        //添加到購物車中
                        buyerCart.addItem(buyerItem);
                    }
                }
            }
        }
        
        return buyerCart;
    }

1) 當我們購買的商品只要有一件是無貨的狀態, 那么刷新購物車詳情頁面, 回顯無貨的商品狀態. 
2)當購物車中午商品時, 刷新當前頁面.

購物車就這么多東西, 可能講解有不到或者錯誤的地方, 歡迎大家能夠指出來.

本文來自:http://www.cnblogs.com/wang-meng/p/5854773.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM