Create Spring MVC Project
On the Eclipse, create a Spring MVC project
Enter Project Information:
- Name: LearnSpringMVCWithRealApps
- Group: com.demo
- Artifact: LearnSpringMVCWithRealApps
- Description: Learn Spring MVC with Real Apps
- Package: com.demo
Select the technologies and libraries to be used:
- Web
Click Next button to show Site Information for project
Click Finish button to finish create Spring MVC project
Configure pom.xml
<?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>
Configure application.properties
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**
server.port=9596
Create Resources
http://learningprogramming.net/wp-content/uploads/java/spring_mvc
Create new folder named http://learningprogramming.net/wp-content/uploads/java/spring_mvc in src\main\resources\static folder. Copy http://learningprogramming.net/wp-content/uploads/java/spring_mvc need show to this folder
JavaScript
Create new folder named js in src\main\resources\static folder. Copy JQuery and jQuery UI libraries need use to this folder
Entities Class
Create new package, named com.demo.entities. In this package, create entities class as below:
Product Entity
Create new java class, named Product.java
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() {
}
}
Item Entity
Create new java class, named Item.java
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() {
}
}
Models Class
Create new package, named com.demo.models. In this package, create ProductModel class as below:
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;
}
}
Create Controllers
Create new package named com.demo.controllers. In this package, create controllers as below:
Product Controller
Create new java class, named ProductController.java
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";
}
}
Cart Controller
Create new java class, named CartController.java
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");
}
}
Create Views
Create new folders with path webapp\WEB-INF\views in src\main. In views folder, create views as below:
Product View
Create new folders named product. Create new jsp file named index.jsp
<%@ 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="${pageContext.servletContext.contextPath }/resources/js/jquery.js"></script>
<script language="javascript" type="text/javascript"
src="${pageContext.servletContext.contextPath }/resources/js/jquery-ui-1.8.2.custom.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/http://learningprogramming.net/wp-content/uploads/java/spring_mvc/' + 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/http://learningprogramming.net/wp-content/uploads/java/spring_mvc/${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>
Structure of Spring MVC Project
Run Application
Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu
Access index method in product controller with following url: http://localhost:9596/product
Output
Drag product photo from product list to cart
Output
Click Remove link from cart to remove product inside cart