Searching...
Sunday, January 31, 2016

Spring MVC Framework With Bootstrap and Hibernate

January 31, 2016





Spring MVC Framework With Bootstrap and Hibernate

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`)
)


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="java9r.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="spring" match-name="product"/>
</hibernate-reverse-engineering>

HibernateUtil.java
package java9r.util.com;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

@SuppressWarnings("deprecation")
public class HibernateUtil {
private static SessionFactory sessionFactory;

static{
try{
sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Initial sessionFactory creation failed."+ex);
throw new ExceptionInInitializerError(ex);

}
}

public static SessionFactory getSessionFactory() {

return sessionFactory;
}
}

Product.java

package java9r.entites.com;
import java.util.Date;
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;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

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

private Integer id;
private String name;
private Long price;
private Integer quantity;
private String description;
private String photo;
private Boolean active;
private Date createiondate;

public Product() {
}

public Product(Date createiondate) {
this.createiondate = createiondate;
}

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

@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;
}

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "createiondate", nullable = false, length = 19)
public Date getCreateiondate() {
return this.createiondate;
}

public void setCreateiondate(Date createiondate) {
this.createiondate = createiondate;
}

}


ProductModel.java

package java9r.model.com;
import java9r.entites.com.*;

//AbstractModel
public class ProductModel extends AbstractModel<Product>{

public ProductModel(){

super(Product.class);
}
}




AbstractModel.java

package java9r.model.com;

import java.io.Serializable;
import java.util.*;
import java9r.entites.com.*;

import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
public abstract class AbstractModel<T> {

private Class<T> entityClass;
protected final SessionFactory sessionFactory = HibernateUtil
.getSessionFactory();
public AbstractModel(Class<T> entityClass){
this.entityClass = entityClass;
}

public AbstractModel(){

}


@SuppressWarnings("unchecked")
public List<Product> findAll(){
try {
if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
return sessionFactory.getCurrentSession().createCriteria(Product.class)
.list();

} catch (Exception e) {
return null;
}
}


public void update(T instance){
try{

if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
sessionFactory.getCurrentSession().merge(instance);
sessionFactory.getCurrentSession().getTransaction().commit();

}catch (RuntimeException re) {
sessionFactory.getCurrentSession().getTransaction().rollback();
throw re;
}
}


public void delete(Product p){
try {
if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
sessionFactory.getCurrentSession().delete(p);
sessionFactory.getCurrentSession().getTransaction().commit();

} catch (Exception e) {
sessionFactory.getCurrentSession().getTransaction().rollback();
throw e;
}
}


public Product FindParticularProduct(Integer id){
try {
if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
return (Product)sessionFactory.getCurrentSession().createCriteria(Product.class)
.add(Restrictions.eq("id",id)).uniqueResult();


} catch (Exception e) {
return null;
}
}


public void create(T instance){
try{

if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
sessionFactory.getCurrentSession().persist(instance);
sessionFactory.getCurrentSession().getTransaction().commit();

}catch (RuntimeException re) {
sessionFactory.getCurrentSession().getTransaction().rollback();
throw re;
}

}

@SuppressWarnings("unchecked")
public T find(Object PrimaryKey){
try{
if(!sessionFactory.getCurrentSession().getTransaction().isActive())
sessionFactory.getCurrentSession().getTransaction().begin();
return (T) sessionFactory.getCurrentSession().get(entityClass,(Serializable) PrimaryKey);



}catch (RuntimeException re) {
return null;
// TODO: handle exception
}

}
}


ProductController
package java9r.controller.com;  
import java9r.entites.com.Product;
import java9r.model.com.ProductModel;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller("/product")
@RequestMapping
public class ProductController {
private ProductModel pm= new ProductModel();

@RequestMapping(value="/productlist", method = RequestMethod.GET)
public String index(ModelMap mm) {
mm.put("listproduct", pm.findAll());
System.out.println("working");
return "index"; //page name
}

/* @RequestMapping(value="/add", method = RequestMethod.GET)
public String add(ModelMap mm) {
mm.put("pr", new Product());

return "add";
}*/

@RequestMapping(value="/add", method = RequestMethod.POST)
public String add(@ModelAttribute(value="pr") Product pr, ModelMap mm) {
// mm.put("pr", new Product());
this.pm.create(pr);
mm.put("listproduct", pm.findAll());

return "index";
}

@RequestMapping(value="/delete/{id}", method = RequestMethod.GET)

public String delete(@PathVariable(value="id") int id, ModelMap mm) {

mm.put("pr", new Product());

this.pm.delete(this.pm.find(id));
mm.put("listproduct", pm.findAll());
return "index";

}


/*
@RequestMapping(value="/edit/{id}", method = RequestMethod.GET)

public String edit(@PathVariable(value="id") Integer id, ModelMap mm) {
mm.put("pr",pm.find(id));

//mm.put("listproduct", pm.findAll());
return "edit";

}
*/
@RequestMapping(value="/edit", method = RequestMethod.POST)

public String edit(@ModelAttribute(value="pr") Product pr, ModelMap mm) {
this.pm.update(pr);
mm.put("listproduct", pm.findAll());
return "refresh";

}

}



WebContent/WEB-INF/web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVCFrameworkAndHibernate</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>


WebContent/WEB-INF/spring-servlet.xml
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="java9r.controller.com" />

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

<!-- <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.html">indexController</prop>
</props>
</property>
</bean>

<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" /> -->
</beans>

WebContent/index.jsp
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">
<title>Home Page</title>
</head>
<body>
<a href="productlist.html">Product list</a> <br>

</body>
</html>


WebContent/jsp/index.jsp
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 >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<%-- background="${pageContext.request.contextPath}/jsp/java9r.png" --%>
</head>
<body background="${pageContext.request.contextPath}/jsp/java9r.jpg" >
<div class="container" >

<div >
<h2>Product List Using Spring MVC Framework With Bootstrap And Hibernate </h2>
<table class="table">
<tr>
<th></th>
<th class="col-md-2">Id</th>
<th class="col-md-2">Name</th>
<th class="col-md-2">Price</th>
<th class="col-md-2">Quantity</th>

<th class="col-md-4" align="center"><%-- <a href="${pageContext.request.contextPath}/add.html">add</a> --%>
<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#AddModal">Add</button>
</th>
</tr>
<c:forEach var="pr" items="${listproduct}">
<tr>
<td><a href="${pageContext.request.contextPath}/delete/${pr.id }.html" class="btn btn-info btn-sm" onclick="return confirm('Are you sure')">-</a></td>
<td>${pr.id }</td>
<td>${pr.name }</td>
<td>${pr.price }</td>
<td>${pr.quantity }</td>
<td>
<%-- <a href="${pageContext.request.contextPath}/edit/${pr.id }.html" >Edit</a>
--%> <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#EditModal${pr.id }">Edit</button>
<button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#DetailsModal${pr.id }">Details</button>


</td>
</tr>




<!-- Modal Detalis -->
<div class="modal fade" id="DetailsModal${pr.id }" role="dialog">
<div class="modal-dialog">

<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Product Detalis</h4>
</div>
<div class="modal-body">


<div class="form-group">
<label for="usr"> Product Id: ${pr.id }</label>

</div>

<div class="form-group">
<label for="usr">Name : ${pr.name }</label>


</div>

<div class="form-group">
<label for="usr">Price: ${pr.price }</label>


</div>
<div class="form-group">
<label for="usr">Quantity: ${pr.quantity }</label>


</div>


<div class="form-group">
<label for="usr">Description: </label>
${pr.description }
</div>


</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-toggle="modal" data-target="#EditModal${pr.id }" value="Edit">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>



<!-- Modal edit -->
<div class="modal fade" id="EditModal${pr.id }" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->

<form id="pr" method="post" action="edit.html">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Edit Product</h4>
</div>
<div class="modal-body">

<div class="form-group">
<label for="usr">Id:</label>

<input type="text" class="form-control" value="${pr.id }" name="id" id="usr" readonly="readonly">

</div>

<div class="form-group">
<label for="usr">Name:</label>

<input type="text" class="form-control" value="${pr.name }" name="name" id="usr">

</div>

<div class="form-group">
<label for="usr">Price:</label>
<input type="text" class="form-control" value="${pr.price }" name="price" id="usr">

</div>
<div class="form-group">
<label for="usr">Quantity:</label>
<input type="text" class="form-control" value="${pr.quantity }" name="quantity" id="usr">

</div>


<div class="form-group">
<label for="usr">Description:</label>
<input type="text" class="form-control" value="${pr.description }" name="description" id="usr">
</div>


</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" value="Save">
<input type="reset" class="btn btn-default" value="Reset">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>


</c:forEach>
</table>
</div>








<!-- Modal -->
<div class="modal fade" id="AddModal" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->

<form method="post" action="add.html">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Add New Product</h4>
</div>
<div class="modal-body">

<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" name="name" id="usr">

</div>

<div class="form-group">
<label for="usr">Price:</label>
<input type="text" class="form-control" name="price" id="usr">

</div>
<div class="form-group">
<label for="usr">Quantity:</label>
<input type="text" class="form-control" name="quantity" id="usr">

</div>


<div class="form-group">
<label for="usr">Description:</label>
<input type="text" class="form-control" name="description" id="usr">
</div>


</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" value="Save">
<input type="reset" class="btn btn-default" value="Reset">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>



</div>

</body>
</html>


WebContent/jsp/refresh.jsp
  refresh.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">
<title>Insert title here</title>
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=list.html">
</head>
<body>

</body>
</html>

Output







0 comments:

Post a Comment

ads2