java web開發 購物車功能實現

來源:互聯網
上載者:User

購物車的功能實現,查詢的三種方法。

1.用cookie實現購物車;

【缺點】:

單純有cookie實現購物車,這樣的購物車不是很理想,設想一下,如果用戶端的瀏覽器把cookie給禁用了,

這種方法就會在這裡掛掉。2.用seeesion實現購物車;

【缺點】:

session中儲存購物車的資訊,這個只是在一個會話中可用,如果使用者沒有登入,或者說登入了以後,添加購物車,在關閉瀏覽器

或者登出後,之前所添加的購物車就只有掛掉了。

3.用cookie和資料庫(購物車資訊持久化)實現購物車;

主要的流程:

A.使用者登入前的資料流:使用者在沒有登入系統的時候,對喜歡的商品進行添加購物車,那麼這個時候,我們可以把購物車資訊儲存

到cookie中,這裡會涉及到cookie的添加,修改操作;也即如果之前在cookie中不存對應的cookie,則就對cookie進行添加操作。

如果在cookie中存在對應的cookie,那麼,這時候,就要對cookie進行修改操作了(這裡涉及到使用者對同一個商品進行多次添加購物車的情況)。

B.使用者登入後的資料流:使用者在登入後,系統首先做的第一件事就是去擷取對應的cookies,如果存在相關的購物車cookies,那麼就對該購物車

資訊進行相應使用者User的持久化操作,要麼添加,要麼修改。(添加操作:該使用者所對應的購物車如果沒有相應的資訊進行添加操作;修改操作:類似的,

如果存在對應使用者的購物車資訊,就進行修改操作)。使用者登入後,也可以進行購物車的添加操作,不過,這裡不是添加到cookie中,而是直接持久化到資料庫中。

註:使用者登入後的資料都是和資料庫打交道。

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

代碼部分:

註:

1 Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME = "iduona_cashTicket_";

 

  
  1 /**  2      * 使用者登入  3      *   4      * @author hongten  5      */  6     public void login() {  7         //使用者登入的時候,去讀取cookies,並且進行持久話操作,更多的登入操作這裡省略啦....  8         peristShoppingCartWhenUserLogin(newUser);  9         } 10  11 /** 12      * 加入購物車<br> 13      * ============================================<br> 14      * 使用者登入前:<br> 15      * 使用者在選擇現金券的時候,點擊現金券的加入購物車的時候,會把該現金券的資訊(現金券的id,購買數量)<br> 16      * 傳遞到這裡,這時候,後台要做的就是從cookie中查詢出是否有相同的記錄,如果有相同的記錄<br> 17      * 則把相應的記錄更新;否則,就添加新的記錄<br> 18      * 使用者登入後:<br> 19      * 使用者在登入後,如果有添加購物車操作,則不用儲存到cookie中,而是直接持久化購物車資訊<br> 20      *  21      * @throws Exception 22      */ 23     public void addToShoppingCart() throws Exception { 24         if (cashTicket == null || cashTicket.getId() == null || cashTicket.getId() < 1) { 25             write("nullId"); 26         } else if (q == null || q == "") { 27             // 購買數量,預設情況下面為1 28             q = String.valueOf(1); 29         } else { 30             // 讀取所有的cookie 31             Cookie cookies[] = ServletActionContext.getRequest().getCookies(); 32             if (cookies == null || cookies.length < 0) { 33                 // 沒有cookie 34                 System.out.println("there is no any cookie .."); 35             } else { 36                 // 判斷使用者是否登入 37                 if (getUserInSession() == null) { 38                     boolean flag = true; 39                     for (Cookie c : cookies) { 40                         if (c.getName().equals(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME + cashTicket.getId())) { 41                             // 說明已有的cookies中有相應的cookie,就進行更新操作 42                             Integer oldValue = Integer.valueOf(c.getValue()); 43                             Integer newValue = Integer.valueOf(oldValue + Integer.valueOf(q)); 44                             fixCookie(c, newValue.toString().trim()); 45                             flag = false; 46                         } 47                     } 48                     // 說明已有的cookies中沒有相應的cookie,就進行添加操作 49                     if (flag) { 50                         addCookie(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME + cashTicket.getId(), q.trim()); 51                     } 52  53                     // ================================================== 54                     // 測試用,讀取所有的cookies 55                     readShoppingCartFromCookie(); 56                     // ================================================== 57  58                     write("success"); 59                 } else { 60                     // 如果使用者登入,說明session存在user,這時就持久化購物車資訊 61                     CashTicket cashTicketTemp = cashTicketService.get(cashTicket.getId()); 62                     if (shoppingCartService.isExistUserAndCashTicket(getUserInSession(), cashTicketTemp)) { 63                         ShoppingCart oldShoppingCart = shoppingCartService.getByUserAndCashTicket(getUserInSession(), cashTicketTemp); 64                         oldShoppingCart.setAmount(oldShoppingCart.getAmount() + Integer.valueOf(q)); 65                         if (shoppingCartService.update(oldShoppingCart)) { 66                             write("success"); 67                         } 68                     } else { 69                         ShoppingCart shoppingCartTemp = new ShoppingCart(); 70                         shoppingCartTemp.setAmount(Integer.valueOf(q)); 71                         shoppingCartTemp.setUser(getUserInSession()); 72                         shoppingCartTemp.setCashTicket(cashTicketTemp); 73                         shoppingCartTemp.setCreateTime(new Date()); 74                         shoppingCartTemp.setStatusType(StatusType.POSITIVE); 75                         shoppingCartTemp.setUuid(UUID.randomUUID().toString()); 76                         if (shoppingCartService.save(shoppingCartTemp)) { 77                             write("success");
 78                         } 79                     } 80                 } 81             } 82         } 83     } 84  85 /** 86      * 從cookie中讀取購物車資訊 87      *  88      * @throws Exception 89      * @return 90      */ 91     public void readShoppingCartFromCookie() throws Exception { 92         System.out.println("======================================================"); 93         Cookie cookies[] = ServletActionContext.getRequest().getCookies(); 94         if (cookies == null || cookies.length < 0) { 95             // System.out.println("there is no any cookie .."); 96             // 沒有cookie 97         } else { 98             for (Cookie c : cookies) { 99                 System.out.println("haha there are many cookies :" + c.getName() + "    " + c.getValue());100             }101         }102     }103 104     /**105      * 添加cookie操作106      * 107      * @param name108      *            cookie的name109      * @param value110      *            cookie的value111      */112     public void addCookie(String name, String value) {113         Cookie cookie = new Cookie(name.trim(), value.trim());114         cookie.setMaxAge(2 * 60 * 60 * 1000);// 設定為2個鐘115         ServletActionContext.getResponse().addCookie(cookie);116     }117 118     /**119      * 更新cookie操作120      * 121      * @param c122      *            要修改的cookie123      * @param value124      *            修改的cookie的值125      */126     public void fixCookie(Cookie c, String value) {127         c.setValue(value.trim());128         c.setMaxAge(2 * 60 * 60 * 1000);// 設定為2個鐘129         ServletActionContext.getResponse().addCookie(c);130     }131 132     /**133      * 當使用者登入的時候,持久化cookie中的購物車資訊,更新為本使用者的購物車資訊134      */135     public void peristShoppingCartWhenUserLogin(User user) {136         if (null != user) {137             Cookie cookies[] = ServletActionContext.getRequest().getCookies();138             if (cookies != null) {139                 for (Cookie c : cookies) {140                     if (c.getName().startsWith(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME)) {141                         // 擷取cookie的名稱:"iduona_cashTicket_45" 和 cookie的值: "21"142                         String name = c.getName();143                         Integer amount = Integer.valueOf(Integer.valueOf(c.getValue())+Integer.valueOf(q));144                         Integer ct_id = Integer.valueOf(name.substring(name.lastIndexOf("_") + 1));145                         CashTicket temp = cashTicketService.get(ct_id);146                         ShoppingCart shoppingCartTemp = new ShoppingCart();147                         if (null != temp) {148                             if (shoppingCartService.isExistUserAndCashTicket(user, temp)) {149                                 // 進行更新操作150                                 ShoppingCart oldShoppingCart = shoppingCartService.getByUserAndCashTicket(user, temp);151                                 oldShoppingCart.setAmount(amount);152                                 shoppingCartService.update(oldShoppingCart);153                             } else {154                                 // 否則進行儲存記錄155                                 shoppingCartTemp.setAmount(amount);156                                 shoppingCartTemp.setUser(user);157                                 shoppingCartTemp.setCashTicket(temp);158                                 shoppingCartTemp.setCreateTime(new Date());159                                 shoppingCartTemp.setStatusType(StatusType.POSITIVE);160                                 shoppingCartTemp.setUuid(UUID.randomUUID().toString());161                                 shoppingCartService.save(shoppingCartTemp);162                             }163                         }164                     }165                 }166                 // 移除所有的現金券cookies167                 removeAllCookies();168             }169         }170     }171 172     /**173      * 移除所有的現金券cookies操作174      */175     public void removeAllCookies() {176         Cookie cookies[] = ServletActionContext.getRequest().getCookies();177         if (cookies == null || cookies.length < 0) {178             // 沒有cookie179             System.out.println("there is no any cookie ..");180         } else {181             System.out.println("開始刪除cookies..");182             for (Cookie c : cookies) {183                 if (c.getName().startsWith(Conf.IDUONA_CASHTICKET_COOKIE_STARTNAME)) {184                     c.setMaxAge(0);// 設定為0185                     ServletActionContext.getResponse().addCookie(c);186                 }187             }188         }189     }

這是部分代碼....

效果:

使用者沒有登入的情況下

使用者登入了以後:

資料庫裡面的情況:

登入前資料

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.