Add and remove items to cart, and view its content.

Introducing the shopping cart

No real store without a shopping cart. First we get the shopping cart status and content to display them on the header of each page. Because this object is required in almost every page, we initialize it in a @ModelAttribute method. We also made a bit of refactoring here, transfering the brands and categories grabing code into the same method.


@ModelAttribute
public void commonAttributes(Model model){
    model.addAttribute("cart", shoppingCartService.get());
    model.addAttribute("categories", categoryService.findAll());
    model.addAttribute("brands", brandService.findAll());
}

Then display the status and content of the shopping cart in the header of the main layout template layout.html


<h3>
    $<span id="cart_total" class="simpleCart_total" th:text="${cart.total}"> 0.00 </span>
    (<span id="cart_items_count" class="simpleCart_quantity" th:text="${#lists.size(cart.items)}">
     </span><span>Items</span>)
    <img src="/images/bag.png" alt="" />
</h3>

Add items the shopping cart

We use AJAX to make a HTTP POST to our backend call with information about the item to add to the shopping cart, view js/cart.js file which contains the javascript AJAX code.

This is how to add the item to the cart, it is as simple as a single method call.


@RequestMapping(method = RequestMethod.POST, path = "/cart", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Op addToCart(@ModelAttribute LineItem item){
    try {
        ShoppingCart sc = shoppingCartService.addItem(item);
        return new Op<>("success", "Item added successfully!", sc);
    }catch (RuntimeException e) {
        return new Op("error", e.getMessage());
    }
}

View the shopping cart

In a previous step (Introducing the shopping cart), we learned how to get the shopping cart, and displayed its status, We put that code in a @ModelAttribute method so it is available in every page. Now all what we need is to write the view template to display full content of the shopping cart.


<h2>MY SHOPPING CART </h2>
<h1 th:if="${#lists.isEmpty(cart.items)}">No Items in your cart yet</h1>
<div th:unless="${#lists.isEmpty(cart.items)}" class="cart-gd">


    <div class="cart-header" th:id="${item.id}" th:each="item : ${cart.items}">

        <a href="#" class="close1 deleteItem" th:attr="data-item-id=${item.id}"> </a>
        <div class="cart-sec simpleCart_shelfItem">
            <div class="cart-item cyc">
                <img th:src="${item.product.mainPhoto.url}" class="img-responsive" alt="" />
            </div>
            <div class="cart-item-info">
                <h3><a href="#" th:text="${item.product.title}"> Lorem Ipsum is not simply </a></h3>

                <div class="delivery">
                    <p>
                        <span>Unit price : $</span> <span th:text="${item.unitPrice}">10.00</span>
                        <br />
                        <span>Quantity : </span> <span th:text="${item.quantity}">10.00</span>
                        <br />
                        <span>Total price : $</span> <span th:text="${item.total}">10.00</span>
                        <br />
                    </p>
                    <div class="clearfix"></div>
                </div>
            </div>
            <div class="clearfix"></div>

        </div>
    </div>
    <div style="margin-top: 50px; text-align: right;">
        <a href="/orders/checkout" class="big_button">Checkout</a>
    </div>
</div>

Delete items from the cart


@RequestMapping(method = RequestMethod.DELETE, path = "/cart/{itemId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Op removeFromCart(@PathVariable("itemId") String itemId){
    try {
        ShoppingCart sc = shoppingCartService.delete(itemId);
        return new Op<>("success", "Item removed successfully!", sc);
    }catch (RuntimeException e) {
        return new Op("error", e.getMessage());
    }
}