Searching...
Monday, May 2, 2016

Spring MVC And Hibernate Shopping Cart

May 02, 2016



Database
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`quantity` int(45) DEFAULT NULL,
`description` varchar(450) DEFAULT NULL,
`photo` varchar(45) DEFAULT NULL,
`active` tinyint(1) DEFAULT NULL,
`createiondate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)


index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=product/productlist.html">
<title>Home</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/product/productlist.html">Shopping</a>

</body>
</html>



web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SpringMVCAndHibernateShopping</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>


spring-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:component-scan base-package="com.java9r" />

<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/product" />
<property name="username" value="root" />
<property name="password" value="ravi" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />


<property name="packagesToScan"><list><value>entites.com</value></list></property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>




<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>


ProductController.java


package com.java9r.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.java9r.service.ProductService;
import org.apache.log4j.Logger;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
private static Logger logger = Logger.getLogger(ProductController.class);
@Autowired
private ProductService productService;

@RequestMapping(value = "/productlist", method = RequestMethod.GET)
public String index(ModelMap mm) {

logger.debug(">> getproductlist ");

mm.put("listproduct", productService.findAll());

logger.debug(">> getproductlist success ");
return "index";
}

}



ShoppingCartController.java


package com.java9r.controller;

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

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.java9r.service.ProductService;

import entites.com.Items;

@Controller
@RequestMapping(value = "/shoppingcart")
public class ShoppingCartController {
@Autowired
private ProductService pm;

@SuppressWarnings("unchecked")
@RequestMapping(value = "/ordernow/{id}", method = RequestMethod.GET)
public String ordernow(@PathVariable(value = "id") int id, ModelMap mm, HttpSession session) {

if (session.getAttribute("cart") == null) {
List<Items> cart = new ArrayList<Items>();
cart.add(new Items(this.pm.find(id), 1));
session.setAttribute("cart", cart);
} else {
List<Items> cart = (List<Items>) session.getAttribute("cart");

// using method isExisting here
int index = isExisting(id, session);
if (index == -1)
cart.add(new Items(this.pm.find(id), 1));
else {
int quantity = cart.get(index).getQuantity() + 1;
cart.get(index).setQuantity(quantity);
}

session.setAttribute("cart", cart);
}

return "cart"; // page name
}

@SuppressWarnings("unchecked")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable(value = "id") int id, HttpSession session) {
List<Items> cart = (List<Items>) session.getAttribute("cart");

int index = isExisting(id, session);
cart.remove(index);
session.setAttribute("cart", cart);
return "cart";
}

@SuppressWarnings("unchecked")
private int isExisting(int id, HttpSession session) {

List<Items> cart = (List<Items>) session.getAttribute("cart");

for (int i = 0; i < cart.size(); i++)

if (cart.get(i).getProduct().getId() == id)
return i;

return -1;
}

}


ProductService.java


package com.java9r.service;
import java.util.List;

import entites.com.Product;



public interface ProductService {


public List<Product> findAll();

public Product find(int id);


}



ProductServiceImpl.java


package com.java9r.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java9r.dao.ProductDAO;

import entites.com.Product;

import org.springframework.transaction.annotation.Propagation;

@Service("ProductService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ProductServiceImpl implements ProductService {
private static Logger logger = Logger.getLogger(ProductServiceImpl.class);

@Autowired
private ProductDAO productDAO;

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
@Override
public List<Product> findAll() {
logger.debug(">> getproductlist ");
return productDAO.findAll();
}

@Override
public Product find(int id) {
return productDAO.find(id);
}


}

Product.java


package entites.com;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "product", catalog = "product")
public class Product implements java.io.Serializable {

/**
*
*/
private static final long serialVersionUID = 4944996330481631983L;
private Integer id;
private String name;
private Long price;
private Integer quantity;
private String description;
private String photo;
private Boolean active;

public Product() {
}

public Product(String name, Long price, Integer quantity, String description, String photo, Boolean active) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.description = description;
this.photo = photo;
this.active = active;
}

@Id
@GeneratedValue(strategy = IDENTITY)

@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}

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

@Column(name = "name", length = 45)
public String getName() {
return this.name;
}

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

@Column(name = "price", precision = 10, scale = 0)
public Long getPrice() {
return this.price;
}

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

@Column(name = "quantity")
public Integer getQuantity() {
return this.quantity;
}

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

@Column(name = "description", length = 450)
public String getDescription() {
return this.description;
}

public void setDescription(String description) {
this.description = description;
}

@Column(name = "photo", length = 45)
public String getPhoto() {
return this.photo;
}

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

@Column(name = "active")
public Boolean getActive() {
return this.active;
}

public void setActive(Boolean active) {
this.active = active;
}

}



Items.java


package entites.com;



public class Items {

private Product product=new 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 Items(Product product, int quantity) {
super();
this.product = product;
this.quantity = quantity;
}

public Items() {
super();
}



}



hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory >
<!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">ravi</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/product</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">product</property>
<property name="hibernate.current_session_context_class">thread</property> -->
<mapping class="entites.com.Product"/>
</session-factory>
</hibernate-configuration>



hibernate.reveng.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
<table-filter match-catalog="product" match-name="product"/>
</hibernate-reverse-engineering>


index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index Page</title>
</head>
<body>
<center><h1>Spring MVC And Hibernate Shopping Cart</h1></center>

<table border="3" align="center" ><tr>

<td>Id</td>
<td>Photo</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Description</td>


</tr>

<c:forEach var="p" items="${listproduct}">


<tr>

<td>${p.id }</td>
<td>
<img alt="" src="${pageContext.request.contextPath}/images/${p.photo}" height="100px" width="100px">

</td>
<td>${p.name}</td>
<td>${p.price}</td>
<td>${p.quantity}</td>
<td>${p.description}</td>



<td><a href="${pageContext.request.contextPath}/shoppingcart/ordernow/${p.id }.html" >OrderNow</a></td>

</tr>

</c:forEach>
</table>
</body>
</html>


cart.jsp



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cart</title>
</head>
<body>

<div align="center">
<h1>Spring MVC And Hibernate Shopping Cart</h1>
<table border="2" >
<tr>
<th>Options</th>
<th >Id</th>
<th>Photo</th>
<th >Name</th>
<th >Price</th>
<th >Quantity</th>
<th >Sub Total</th>


</tr>

<c:set var="s" value="0"></c:set>
<c:forEach var="pr" items="${sessionScope.cart}">
<c:set var="s" value="${s+ pr.product.price * pr.product.quantity}"></c:set>
<tr>
<td><a href="${pageContext.request.contextPath}/shoppingcart/delete/${pr.product.id }.html" >Remove</a></td>
<td>${pr.product.id }</td>

<td>
<img alt="" src="${pageContext.request.contextPath}/images/${pr.product.photo}" height="100px" width="100px">

</td>

<td>${pr.product.name }</td>
<td>${pr.product.price }</td>
<td>${pr.product.quantity }</td>
<td>${pr.product.price * pr.product.quantity}</td>
</tr>






</c:forEach>

<tr><td colspan="6" align="right">Sum</td>
<td>${s}</td>

</tr>
</table>
<a href="${pageContext.request.contextPath}/product/productlist.html">Shoping</a> <br>

</div>



</body>
</html>




14 comments:

  1. Replies
    1. Please Download From github

      https://github.com/ravi900kumar/SpringMVCAndHibernateShopping

      Delete
  2. can u send url of this project on my mail id
    chaman1989srivastav@gmail.com

    ReplyDelete
    Replies
    1. Please Download From github

      https://github.com/ravi900kumar/SpringMVCAndHibernateShopping

      Delete
  3. Sir, pls make a video how to add all java files and images, etc in the project explorer.

    ReplyDelete
  4. hello
    how to connect data base to this project ???

    ReplyDelete
  5. https://www.floraindia.com/flower-delivery/delhi.html Want to play games online but don't know where or how to get started or what's currently out there? This article provides a quick overview of the current online gaming scene.

    ReplyDelete
  6. https://www.visualaidscentre.com/lasik-surgery-in-gurgaon/ Every patient needs some help deciding who should perform their LASIK surgery in Michigan. But how do you decide?? These articles will give patients some important information that must be considered!

    ReplyDelete
  7. Sees for paper an especially manager diagram, I reeled close to your blog other than eliminate up a bound report. I need your improvement for scratching... 토토사이트

    ReplyDelete
  8. The editors might dismiss your shop all together and search for one more customer to finish it.
    www.pureparima.com

    ReplyDelete

ads2