Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the principle of Shopping cart and its Java implementation

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to understand the shopping cart principle and Java implementation, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Today, to write about shopping carts, here are four questions:

1) the user does not log in the user name and password, adds the product, closes the browser and then opens it, does not log in the user name and password Q: is the shopping cart product still there?

2) the user logs in with the username and password, adds the product, closes the browser and then opens it without logging in. Ask: is the shopping cart product still there?

3) the user logs in the user name and password, adds the product, closes the browser, and then opens it. The login user name and password ask: is the shopping cart product still there?

4) the user logs in the username and password, adds the product, closes the browser, opens the browser at home and asks: is the shopping cart product still there?

The above four questions are all based on JD.com, so guess what the result is?

1) in

2) gone

3) in

4) in

If you can guess the answer, then you are really good, so how do you achieve these four points? (if you have a disapproving partner, you can experiment with JD.com.)

Next, let's explain the principle of shopping cart, and then talk about the specific implementation of code.

1) the user does not log in and adds the item, which is added to the Cookie of the browser, so when you visit it again (do not log in), the item is still in the Cookie, so the item in the shopping cart still exists.

2) when the user logs in and adds items, both the items in Cookie and the items selected by the user will be added to the shopping cart, and then the items in Cookie will be deleted. So when the user visits again (does not log in), the shopping cart item in Cookie has been deleted, so the shopping cart item is gone.

3) when the user logs in and adds the item, the item is added to the database for persistent storage, and the login user name and password are opened again. The product selected by the user must still exist, so the item in the shopping cart still exists.

4) reason 3)

Here again, the advantages of saving items to Cookie without login and the comparison between saving to Session and database:

1:Cookie: pros: save user browsers (don't waste our company's servers) disadvantages: Cookie disabled, do not provide save

2:Session: (Redis: waste a lot of server memory: implement, disable Cookie) very fast

3: the speed of database (Mysql, Redis, SOlr) is too slow if it can be persisted.

So what I'm going to talk about today is:

User not logged in: shopping cart added to Cookie

User login: save the shopping cart to Redis (no database)

Illustration of the overall thinking:

Then there is a code example to implement the function of the shopping cart:

First, let's take a look at the design of the shopping cart and the shopping item JavaBean:

Shopping cart: buyerCart.java

1 public class BuyerCart implements Serializable {/ * shopping cart * / private static final long serialVersionUID = 1L; / / Product result set private List items = new ArrayList () / / add shopping items to shopping cart public void addItem (BuyerItem item) {/ / determine whether to include the same if (items.contains (item)) {/ / additional quantity for (BuyerItem buyerItem: items) {if (buyerItem.equals (item)) {buyerItem .setAmount (item.getAmount () + buyerItem.getAmount ()) } else {items.add (item);}} public List getItems () {return items;} public void setItems (List items) {this.items = items } / / subtotal / / quantity of goods @ JsonIgnore public Integer getProductAmount () {Integer result = 0; / / calculate for (BuyerItem buyerItem: items) {result + = buyerItem.getAmount ();} return result } / / Commodity amount @ JsonIgnore public Float getProductPrice () {Float result = 0f; / / calculate for (BuyerItem buyerItem: items) {result + = buyerItem.getAmount () * buyerItem.getSku (). GetPrice ();} return result } / / Freight @ JsonIgnore public Float getFee () {Float result = 0f; / / calculate if (getProductPrice ()

< 79) { result = 5f; } return result; } //总价 @JsonIgnore public Float getTotalPrice(){ return getProductPrice() + getFee(); } } 这里使用了@JsonIgonre注解是因为下面需要将BuyerCart 转换成Json格式, 而这几个字段只有get 方法, 所以不能转换, 需要使用忽略Json。 下面是购物项: buyerItem.java public class BuyerItem implements Serializable{ private static final long serialVersionUID = 1L; //SKu对象 private Sku sku; //是否有货 private Boolean isHave = true; //购买的数量 private Integer amount = 1; public Sku getSku() { return sku; } public void setSku(Sku sku) { this.sku = sku; } public Boolean getIsHave() { return isHave; } public void setIsHave(Boolean isHave) { this.isHave = isHave; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sku == null) ? 0 : sku.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) //比较地址 return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BuyerItem other = (BuyerItem) obj; if (sku == null) { if (other.sku != null) return false; } else if (!sku.getId().equals(other.sku.getId())) return false; return true; } } 1、将商品加入购物车中 //加入购物车 function addCart(){ // + skuId _window.location.href="/shopping/buyerCart?skuId="+skuId+"&amount="+$("#buy-num").val(); } 这里传入的参数是skuId(库存表的主键, 库存表保存的商品id,颜色,尺码,库存等信息), 购买数量amount。 接着我们来看Controller是如何来处理的: //加入购物车 @RequestMapping(value="/shopping/buyerCart") public 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 () {/ / Shopping cart object and json string interconversion buyerCart = om.readValue (cookie.getValue (), BuyerCart.class); break } / / 2 there is no shopping cart in the null cookie. Create the shopping cart object if (buyerCart = = buyerCart) {shopping = new BuyerCart () } / / 3, append the current item to the shopping cart if (null! = skuId & & null! = amount) {Sku sku = new Sku (); sku.setId (skuId); BuyerItem buyerItem = new BuyerItem (); buyerItem.setSku (sku) / / set the number of buyerItem.setAmount (amount); / / add shopping items to the shopping cart buyerCart.addItem (buyerItem);} / / sort reverse List items = buyerCart.getItems () Collections.sort (items, new Comparator () {@ Override public int compare (BuyerItem o1, BuyerItem O2) {return-1;}}) / / the first three logins and non-logins do the same operation. In the fourth point, you need to judge that String username = sessionProviderService.getAttributterForUsername (RequestUtils.getCSessionId (request, response)); if (null! = username) {/ / login / / 4, append the shopping cart to Redis cartService.insertBuyerCartToRedis (buyerCart, username) / / 5, clear the Cookie and set the survival time to 0, and immediately destroy Cookie cookie = new Cookie (Constants.BUYER_CART, null); cookie.setPath ("/"); cookie.setMaxAge (- 0); response.addCookie (cookie) } else {/ / not logged in / / 4, save the shopping cart to Cookie / / convert the object to json format Writer w = new StringWriter (); om.writeValue (w, buyerCart); Cookie cookie = new Cookie (Constants.BUYER_CART, w.toString ()) / / set path to be able to share cookie cookie.setPath ("/"); / / set Cookie expiration time:-1 means to close the browser to expire 0: immediately expire > 0: in seconds, how many seconds will expire after cookie.setMaxAge (24,60,60) / / 5Cookie Writing browser response.addCookie (cookie);} / / 6, redirect return "redirect:/shopping/toCart";}

Here is a knowledge point: convert an object into a json string / json string into an object

Let's write a small Demo here to demonstrate the conversion between json and objects, using the ObjectMapper class in springmvc.

Public class TestJson {@ Test public void testAdd () throws Exception {TestTb testTb = new TestTb (); testTb.setName ("Fan Bingbing"); ObjectMapper om = new ObjectMapper (); om.setSerializationInclusion (Include.NON_NULL); / / convert the object to the json string Writer wr = new StringWriter (); om.writeValue (wr, testTb) System.out.println (wr.toString ()); / / return object TestTb r = om.readValue (wr.toString (), TestTb.class); System.out.println (r.toString ());}}

Execution result:

Here we use Include.NON_NULL. If the attribute in TestTb is null, it will not be converted to Json. From the object-- > Json string, use objectMapper.writeValue (). From the Json string-- > object uses objectMapper.readValue ().

Return to the code in our project above and add this item to Cookie only if you are not logged in to add it.

/ / not logged in / / 4, save the shopping cart to Cookie / / convert the object to json format Writer w = new StringWriter (); om.writeValue (w, buyerCart); Cookie cookie = new Cookie (Constants.BUYER_CART, w.toString ()); / / set path to share cookie cookie.setPath ("/") / / set Cookie expiration time:-1 means to close the browser to expire 0: immediately expire > 0: unit: seconds, how many seconds will expire cookie.setMaxAge (24060060); / / 5Cookie write browser response.addCookie (cookie)

We debug can see:

Here you have converted the object shopping cart object buyerCart to Json format.

Add items to the shopping cart, whether you are logged in or not, first take out the shopping cart in Cookie, and then append the currently selected item to the shopping cart.

Then, if you log in, empty the shopping cart in Cookie and add the contents of the shopping cart to Redis for persistence.

If not logged in, append the selected item to Cookie.

The code to append the shopping cart to Redis: insertBuyerCartToRedis (this includes determining whether the same item is added)

/ / Save the shopping cart to Redis public void insertBuyerCartToRedis (BuyerCart buyerCart, String username) {List items = buyerCart.getItems (); if (items.size () > 0) {/ / redis saves the Map collection with skuId as key and amount as value Map hash = new HashMap () For (BuyerItem item: items) {/ / determine whether there is the same 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) }

Determine whether the user is logged in: String username =

SessionProviderService.getAttributterForUsername (RequestUtils.getCSessionId (request, response))

Public class RequestUtils {/ / get CSessionID public static String getCSessionId (HttpServletRequest request, HttpServletResponse response) {/ / 1, and get Cookie Cookie [] cookies = request.getCookies () from Request / / 2, traverse the search from the Cookie data and take CSessionID if (null! = cookies & & cookies.length > 0) {for (Cookie cookie: cookies) {if ("CSESSIONID" .equals (cookie.getName () {/ / and return return cookie.getValue () directly. } / / No, create a CSessionId, put it in Cookie and return to the browser. Return the new CSessionID String csessionid = UUID.randomUUID (). ToString (). ReplaceAll ("-", "); / / and put it in Cookie Cookie cookie = new Cookie (" CSESSIONID ", csessionid); / / cookie brings it every time, set the path cookie.setPath (" / "); / / 0: close the browser and destroy the cookie. 0: disappear immediately. > 0 survival time, second cookie.setMaxAge (- 1); return csessionid;}} / / get public String getAttributterForUsername (String jessionId) {String value = jedis.get (jessionId + ": USER_NAME"); if (null! = value) {/ / calculate the session expiration time is the starting time of a user * * request. Jedis.expire (jessionId + ": USER_NAME", 60*exp); return value;} return null;}

2. Shopping cart display page

* Redirect to the shopping cart display page: return "redirect:/shopping/toCart". There are two ways to enter the settlement page:

1) Click to add the shopping cart on the product details page.

2) Click the shopping cart button directly to enter the shopping cart checkout page.

Let's take a look at the code on the settlement page:

@ Autowired private CartService cartService / / go to the shopping cart to settle the bill. There are two places to go directly: 1. Click the add shopping cart button 2 in the product details page, and directly click the shopping cart button @ RequestMapping (value= "/ shopping/toCart") public String toCart (Model model, HttpServletRequest request, HttpServletResponse response) throws JsonParseException, JsonMappingException. IOException {/ / converts an object to a json string / json string to an object ObjectMapper om = new ObjectMapper () Om.setSerializationInclusion (Include.NON_NULL); BuyerCart buyerCart = null; / / 1, get the shopping cart Cookie [] cookies = request.getCookies () in Cookie If (null! = cookies & & cookies.length > 0) {for (Cookie cookie: cookies) {/ / if (Constants.BUYER_CART.equals (cookie.getName () {/ / Shopping cart object and json string convert buyerCart = om.readValue (cookie.getValue ()) BuyerCart.class) Break;} / / determine whether to log in String username = sessionProviderService.getAttributterForUsername (RequestUtils.getCSessionId (request, response)) If (null! = username) {/ / logged in / / 2, if there is something in the shopping cart, save the shopping cart contents to Redis if (null = = buyerCart) {cartService.insertBuyerCartToRedis (buyerCart, username) / / clear Cookie to set the survival time to 0, and immediately destroy Cookie cookie = new Cookie (Constants.BUYER_CART, null); cookie.setPath ("/"); cookie.setMaxAge (- 0); response.addCookie (cookie) } / / 3, take out the shopping cart buyerCart = cartService.selectBuyerCartFromRedis (username) in the Redis;} / / 4, create the shopping cart if (null = = buyerCart) {buyerCart = new BuyerCart () } / / 5, fill the shopping cart. Just load the skuId into the shopping cart. Here you also need to find out the sku details List items = buyerCart.getItems () If (items.size () > 0) {/ / sku related information can be added to shopping items only if there are items in the shopping cart. For (BuyerItem buyerItem: items) {buyerItem.setSku (cartService.selectSkuById (buyerItem.getSku (). GetId () }} / / 5, the shopping cart is already full. Here we directly echo the page model.addAttribute ("buyerCart", buyerCart); / / jump to the shopping page return "cart";}

Here is the shopping cart details display page, it should be noted that if the same item is continuously added, it needs to be merged.

The shopping cart details display page includes two parts: 1) merchandise details 2) Total (total merchandise, freight)

Among them, 1) the details of the goods include the size, color, quantity and availability of the goods.

Take out the shopping cart from Redis: buyerCart = cartService.selectBuyerCartFromRedis (username)

/ / take out the shopping cart public BuyerCart selectBuyerCartFromRedis (String username) {BuyerCart buyerCart = new BuyerCart () in Redis; / / get all the items. What is saved in redis is the Map collection with skuId as key and amount as value Map hgetAll = jedis.hgetAll ("buyerCart:" + username); Set entrySet = hgetAll.entrySet () For (Entry 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 (); / / add buyerCart.addItem (buyerItem) to the shopping cart;} return buyerCart;}

Fill up the shopping cart. Just load the skuId into the shopping cart. Here you also need to find out the sku details: List items = buyerCart.getItems ()

BuyerItem.setSku (cartService.selectSkuById (buyerItem.getSku (). GetId ()

/ add appropriate data to the shopping items in the shopping cart, query sku objects, color objects, public Sku selectSkuById (Long skuId) {Sku sku = skuDao.selectByPrimaryKey (skuId) through skuId; / / Color sku.setColor (colorDao.selectByPrimaryKey (sku.getColorId (); / / add product information sku.setProduct (productDao.selectByPrimaryKey (sku.getProductId () Return sku;}

Then return to "cart.jsp", which is the shopping cart details display page.

3. Go to the settlement page

This means that the user must log in, and there must be items in the shopping cart.

So here you need to make use of the filtering function of springmvc. Users must log in when they click on the settlement. If they do not log in, they will be prompted to log in.

/ / to settle @ RequestMapping (value= "/ buyer/trueBuy") public String trueBuy (String [] skuIds, Model model, HttpServletRequest request, HttpServletResponse response) {/ / 1, shopping cart must have goods, / / take out user name and then take out shopping cart String username = sessionProviderService.getAttributterForUsername (RequestUtils.getCSessionId (request, response)) / / take out all shopping carts BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds (skuIds, username); List items = buyerCart.getItems (); if (items.size () > 0) {/ / there are items in the shopping cart / / to determine whether all the checked items are in stock. If one item is out of stock, refresh the page. Boolean flag = true; / / 2, items in the shopping cart must be in stock and are considered out of stock when the purchase quantity is greater than the inventory quantity. Tip: the original page of the shopping cart does not move. Change from stock to out of stock, add red reminder. For (BuyerItem buyerItem: items) {/ / A shopping item full of shopping carts. SkuId is the only item in the current shopping item. We also need the number of shopping items to determine whether there is any buyerItem.setSku (cartService.selectSkuById (buyerItem.getSku (). GetId () / / check inventory if (buyerItem.getAmount () > buyerItem.getSku (). GetStock ()) {/ / out of stock buyerItem.setIsHave (false); flag = false } if (! flag) {/ / No goods, the original page does not move, change goods to no goods, refresh the page. Model.addAttribute ("buyerCart", buyerCart); return "cart";} else {/ / Shopping cart has no merchandise / / No merchandise: 1 > original shopping cart page refresh (shopping cart page indicates no merchandise) return "redirect:/shopping/toCart" } / / 3, normally enter the next page return "order";}

Check out the specified shopping cart, because the items we need to buy will be checked on the shopping cart details page before we settle the check, so the checkout is based on the checked items.

BuyerCart buyerCart = cartService.selectBuyerCartFromRedisBySkuIds (skuIds, username)

Take the specified item out of the shopping cart:

/ / take the specified item public BuyerCart selectBuyerCartFromRedisBySkuIds (String [] skuIds, String username) {BuyerCart buyerCart = new BuyerCart () from the shopping cart; / / get all the items. The Map collection of skuId is key and amount is value Map hgetAll = jedis.hgetAll ("buyerCart:" + username); if (null! = hgetAll & & hgetAll.size () > 0) {Set entrySet = hgetAll.entrySet () For (Entry 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 () / / add buyerCart.addItem (buyerItem) to the shopping cart;} return buyerCart;}

1) when we buy only one item that is out of stock, refresh the shopping cart details page to show the status of the item that is out of stock.

2) refresh the current page when the shopping cart is purchased at noon.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report