Create Database
Create a database with the name is learnjspservlet. This database have a table: Product
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`price` double NOT NULL,
`quantity` int(11) NOT NULL,
`status` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`name`, `price`, `quantity`, `status`) VALUES
('Name 1', 4.5, 10, 1),
('Name 2', 7, 2, 0),
('Name 3', 8, 4, 1);
Product Structure Table
Product Data Table
Create Maven Project
On the Eclipse, create a Maven project
Click Next button to select Workspace Location for project
Click Next button to select Archetype for project
Click Next button and enter Project Information:
- Group Id: LearnJSPServletWithRealApps
- Artifact Id: LearnJSPServletWithRealApps
- Package: com.demo
Click Finish button to finish create Maven project
Configure pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>LearnJSPServletWithRealApps</groupId>
<artifactId>LearnJSPServletWithRealApps</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Learn JSP-Servlet with Real Apps</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<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>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.CR1</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.0.CR1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>LearnJSPServletWithRealApps</finalName>
</build>
</project>
Configure web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Redirect Page
Create new JSP file named index.jsp in src\main\webapp folder.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<jsp:forward page="product"></jsp:forward>
Create Entities
Create new package named com.demo.entities. In this package, create new java class named Product.java as below:
package com.demo.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private double price;
private int quantity;
private boolean status;
public int getId() {
return id;
}
public void setId(int 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 int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
Hibernate Configuration File
Create new xml file named hibernate.cfg.xml in src\main\java folder as below:
<?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.url">jdbc:mysql://localhost:3306/learnjspservlet</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.demo.entities.Product" />
</session-factory>
</hibernate-configuration>
Create HibernateUtil Class
Create new package named com.demo.models. In this package, create new java class named HibernateUtil.java as below:
package com.demo.models;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
} catch (Throwable th) {
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Create Models
Create new package named com.demo.models. In this package, create new java class named ProductModel.java as below:
package com.demo.models;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.demo.entities.Product;
public class ProductModel {
protected SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public List<Product> findAll() {
List<Product> products = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query<Product> query = session.createQuery("from Product", Product.class);
products = query.getResultList();
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return products;
}
public Product find(int id) {
Product product = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query<Product> query = session.createQuery("from Product where id = :id", Product.class);
query.setParameter("id", id);
product = query.getSingleResult();
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return product;
}
public boolean delete(int id) {
boolean result = true;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.delete(this.find(id));
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
result = false;
} finally {
session.close();
}
return result;
}
}
Create Servlets
Create new package named com.demo.servlets. In this package, create new Servlets as below:
Product Servlet
In com.demo.servlets package, create new Servlet named ProductServlet as below:
package com.demo.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.demo.models.ProductModel;
@WebServlet("/product")
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ProductModel productModel = new ProductModel();
String action = request.getParameter("action");
if (action == null) {
request.setAttribute("products", productModel.findAll());
request.getRequestDispatcher("product/index.jsp").forward(request, response);
} else {
if (action.equalsIgnoreCase("delete")) {
int id = Integer.parseInt(request.getParameter("id"));
productModel.delete(id);
response.sendRedirect("product");
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Create JSP Pages
Create new folder named product in src\main\webapp folder. In this folder, create new JSP files as below:
Index Page
In src\main\webapp\product folder, create new JSP file named index.jsp as below:
<%@ 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>
<title>CRUD Operators with Hibernate</title>
</head>
<body>
<h3>Product List</h3>
<table border="1" cellpadding="2" cellspacing="2">
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Price</th>
<th>Quantity</th>
<th>Action</th>
</tr>
<c:forEach var="product" items="${products }">
<tr>
<td>${product.id }</td>
<td>${product.name }</td>
<td>${product.status }</td>
<td>${product.price }</td>
<td>${product.quantity }</td>
<td>
<a href="${pageContext.request.contextPath }/product?action=delete&id=${product.id }">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Structure of Maven Project
Run Application
Select project, right click and select Run As/Run on Server menu
Access DemoServlet with following urls as below:
- http://localhost:8081/LearnJSPServletWithRealApps
- http://localhost:8081/LearnJSPServletWithRealApps/product
Output
Click Delete link:
Output