Build Drag and Drop Shopping Cart in Spring MVC Framework

This project will demonstrate how to Build Drag and Drop Shopping Cart in Spring MVC Framework

  • SpringMVCFramework
    • src/main/java
      • com.demo
        • SpringMVCFramework.java
      • com.demo.controllers
        • ProductController.java
        • CartController.java
      • com.demo.entities
        • Product.java
        • Item.java
      • com.demo.models
        • ProductModel.java
    • src/main/resources
      • static
      • templates
      • application.properties
    • src
      • main
        • webapp
          • WEB-INF
            • views
              • product
                • index.jsp
    • pom.xml
package com.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringMVCFramework {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringMVCFramework.class, args);
        }
    }
package com.demo.controllers;

import org.springframework.stereotype.*;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.demo.models.ProductModel;

@Controller
@RequestMapping(value = { "", "product" })
public class ProductController {

    @RequestMapping(method = RequestMethod.GET)
    public String index(ModelMap modelMap) {
        ProductModel productModel = new ProductModel();
        modelMap.put("products", productModel.findAll());
        return "product/index";
    }

}
package com.demo.controllers;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.entities.Item;
import com.demo.models.ProductModel;

@Controller
@RequestMapping(value = "cart")
public class CartController {

    private int isExist(String id, HttpSession session) {
        List<Item> cart = (List<Item>) session.getAttribute("cart");
        for (int i = 0; i < cart.size(); i++) {
            if (cart.get(i).getProduct().getId().equalsIgnoreCase(id)) {
                return i;
            }
        }
        return -1;
    }

    @RequestMapping(value = "buy/{id}", method = RequestMethod.GET)
    @ResponseBody
    public List<Item> buy(@PathVariable(value = "id") String id, HttpSession session) {
        ProductModel productModel = new ProductModel();
        if (session.getAttribute("cart") == null) {
            List<Item> cart = new ArrayList<Item>();
            cart.add(new Item(productModel.find(id), 1));
            session.setAttribute("cart", cart);
        } else {
            List<Item> cart = (List<Item>) session.getAttribute("cart");
            int index = this.isExist(id, session);
            if (index != -1) {
                cart.get(index).setQuantity(cart.get(index).getQuantity() + 1);
            }
            else {
                cart.add(new Item(productModel.find(id), 1));
            }
            session.setAttribute("cart", cart);
        }
        return (List<Item>) session.getAttribute("cart");
    }

    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public List<Item> delete(@PathVariable(value = "id") String id, HttpSession session) {
        List<Item> cart = (List<Item>) session.getAttribute("cart");
        int index = isExist(id, session);
        cart.remove(index);
        session.setAttribute("cart", cart);
        return (List<Item>) session.getAttribute("cart");
    }

}
package com.demo.entities;

public class Product {

    private String id;
    private String name;
    private double price;
    private String photo;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

    public Product(String id, String name, double price, String photo) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.photo = photo;
    }

    public Product() {
    }

}
package com.demo.entities;

public class Item {

    private Product product;
    private int quantity;

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public Item(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }

    public Item() {
    }

}
package com.demo.models;

import java.util.ArrayList;
import java.util.List;

import com.demo.entities.Product;

public class ProductModel {

    public List<Product> findAll() {
        List<Product> products = new ArrayList<Product>();
        products.add(new Product("p1", "Name 1", 100, "thumb1.gif"));
        products.add(new Product("p2", "Name 2", 200, "thumb2.gif"));
        products.add(new Product("p3", "Name 3", 300, "thumb3.gif"));
        return products;
    }

    public Product find(String id) {
        for (Product product : findAll()) {
            if (product.getId().equalsIgnoreCase(id)) {
                return product;
            }
        }
        return null;
    }

}
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

server.port=9596
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Drag and Drop Shopping Cart with Spring MVC Framework</title>

<script language="javascript" type="text/javascript"
    src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script language="javascript" type="text/javascript"
    src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script language="javascript" type="text/javascript">
    $(document).ready(function() {

        $('#listProducts img').css({
            'z-index' : 100
        }).draggable({
            'opacity' : '0.5',
            'revert' : true,
            'cursor' : 'pointer'
        });

        function displayCart(data) {
            var s = '';
            var sum = 0;
            for (var i = 0; i < data.length; i++) {
                sum += parseInt(data[i].quantity) * parseFloat(data[i].product.price);
                s += '<br><img src="${pageContext.servletContext.contextPath }/resources/images/' + data[i].product.photo + '" width="50" height="50">';
                s += '<br>Id: ' + data[i].product.id;
                s += '<br>Name: ' + data[i].product.name;
                s += '<br>Quantity: ' + data[i].quantity;
                s += '<br>Sub Total: ' + (parseInt(data[i].quantity) * parseFloat(data[i].product.price));
                s += '<br><a href="#?productIdCart=' + data[i].product.id + '" class="delete">Delete</a>';
                s += '<br>--------------------------';
            }
            s += '<br>Totals: ' + sum;
            $('#cart').html(s);
        }

        $('#cart').droppable({
            drop: function (event, ui) {
                var productId = $(ui.draggable).siblings('.productId').val();
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    url: '${pageContext.request.contextPath}/cart/buy/' + productId ,
                    success: function (data) {
                        displayCart(data);
                    }
                });
            }
        });

        $('#cart').ajaxComplete(function () {
            $('.delete').bind('click', function () {
                var productIdCart = $(this).attr('href').split('=');
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    url: '${pageContext.request.contextPath}/cart/delete/' + productIdCart[1],
                    success: function (data) {
                        displayCart(data);
                    }
                });
            });
        });


    });
</script>

</head>
<body>

    <div style="float: left; margin-right: 10px;" id="listProducts">
        <table cellpadding="2" cellspacing="2" border="1">
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Price</th>
                <th>Photo</th>
            </tr>
            <c:forEach var="product" items="${products }">
                <tr>
                    <td>${product.id }</td>
                    <td>${product.name }</td>
                    <td>${product.price }</td>
                    <td>
                        <img src="${pageContext.servletContext.contextPath }/resources/images/${product.photo}" width="120" height="100" class="productPhoto" />
                        <input type="hidden" class="productId" value="${product.id}"/>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </div>

    <div id="cart" style="width: 200px; min-height: 200px; border: 1px solid red; margin-left: 300px; padding: 5px;">

    </div>

</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>LearnSpringMVCWithRealApps</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>LearnSpringMVCWithRealApps</name>
    <description>Learn Spring MVC with Real Apps</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- Spring MVC  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JSTL tag lib -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- Tomcat for JSP rendering -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Screenshots