Student
entity for this example. The focus will be on setting up the environment and demonstrating CRUD operations, including creating, reading, updating, and deleting.Introduction
Integrating JSP and Servlets with Hibernate allows for a clean separation of the presentation layer and the data access layer. Hibernate handles the database operations, while JSPs and Servlets manage the user interface and request handling. In this tutorial, we will:
- Set up a Maven project with necessary dependencies.
- Configure Hibernate and MySQL.
- Create an entity class (
Student
). - Create JSPs for the user interface.
- Implement Servlets for handling CRUD operations.
- Use annotations instead of
web.xml
for configuration.
Step 1: Set Up Your Project
1.1 Create a Maven Project
Open your IDE and create a new Maven project.
1.2 Add Dependencies
Update your pom.xml
file to include dependencies for Hibernate, MySQL, JSP, and Servlet API.
<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.example</groupId>
<artifactId>jsp-servlet-hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.0.Final</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>jakarta.servlet.jsp</groupId>
<artifactId>jakarta.servlet.jsp-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 2: Configure Hibernate
2.1 Create hibernate.cfg.xml
Create a hibernate.cfg.xml
file in the src/main/resources
directory to configure database connection settings and Hibernate properties.
<!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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
Replace hibernate_db
, root
, and password
with your MySQL database name and credentials.
Explanation:
hibernate.dialect
specifies the SQL dialect to be used.hibernate.connection.driver_class
specifies the JDBC driver class.hibernate.connection.url
specifies the JDBC URL for the database connection.hibernate.connection.username
andhibernate.connection.password
specify the database credentials.hibernate.hbm2ddl.auto
specifies the schema generation strategy.hibernate.show_sql
specifies whether to show SQL statements in the logs.
Step 3: Create the Entity Class
Create an entity class Student
that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Explanation:
- The
@Entity
annotation specifies that the class is an entity and is mapped to a database table. - The
@Id
annotation specifies the primary key of the entity. - The
@GeneratedValue(strategy = GenerationType.IDENTITY)
annotation specifies that the primary key is auto-incremented.
Step 4: Create JSPs for User Interface
Create a JSP file named index.jsp
in the src/main/webapp
directory to provide a basic user interface.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Student Management</title>
</head>
<body>
<h1>Student Management Application</h1>
<a href="addStudent.jsp">Add Student</a>
<a href="listStudents.jsp">List Students</a>
</body>
</html>
Create addStudent.jsp
to collect student data and submit it to the servlet.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Add Student</title>
</head>
<body>
<h1>Add Student</h1>
<form action="studentServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Create listStudents.jsp
to display the list of students.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>List Students</title>
</head>
<body>
<h1>List of Students</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>
<a href="updateStudent.jsp?id=${student.id}">Edit</a> |
<a href="studentServlet?action=delete&id=${student.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Create updateStudent.jsp
to edit student data.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Update Student</title>
</head>
<body>
<h1>Update Student</h1>
<form action="studentServlet?action=update" method="post">
<input type="hidden" name="id" value="${student.id}">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="${student.name}"><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="${student.email}"><br><br>
<input type="submit" value="Update">
</form>
</body>
</html>
Explanation:
index.jsp
provides links to add and list students.addStudent.jsp
provides a form to collect student data.listStudents.jsp
displays a list of students with edit and delete options.updateStudent.jsp
provides a form to edit student data.
Step 5: Implement Servlets for Handling CRUD Operations
Create a servlet named StudentServlet
to handle student requests.
5.1 Create StudentServlet
package com.example.servlet;
import com.example.entity.Student;
import com.example.util.HibernateUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.io.IOException;
import java.util.List;
@WebServlet("/studentServlet")
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("update".equals(action)) {
updateStudent(request, response);
} else {
addStudent(request, response);
}
}
private void addStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
Student student = new Student();
student.setName(name);
student.setEmail(email);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.persist(student);
transaction.commit();
response.sendRedirect("listStudents.jsp");
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
response.getWriter().println("Error saving student");
} finally {
session.close();
}
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long id = Long.parseLong(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Student student = session.get(Student.class, id);
student.setName(name);
student.setEmail(email);
session.update(student);
transaction.commit();
response.sendRedirect("listStudents.jsp");
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
response.getWriter().println("Error updating student");
} finally {
session.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("delete".equals(action)) {
deleteStudent(request, response);
} else {
listStudents(request, response);
}
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long id = Long.parseLong(request.getParameter("id"));
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Student student = session.get(Student.class, id);
session.delete(student);
transaction.commit();
response.sendRedirect("listStudents.jsp");
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
response.getWriter().println("Error deleting student");
} finally {
session.close();
}
}
private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Session session = HibernateUtil.getSessionFactory().openSession();
List<Student> students = session.createQuery("from Student", Student.class).list();
request.setAttribute("students", students);
request.getRequestDispatcher("listStudents.jsp").forward(request, response);
session.close();
}
}
Explanation:
- The
StudentServlet
class handles POST requests to add or update a student and GET requests to list or delete students.
Step 6: Configure Hibernate Utility Class
Create a utility class HibernateUtil
to manage the Hibernate SessionFactory
.
package com.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
Explanation:
- The
HibernateUtil
class provides a singletonSessionFactory
and a method to shut it down.
Step 7: Run the Application
- Deploy the application to a servlet container like Apache Tomcat.
- Access the application at
http://localhost:8080/jsp-servlet-hibernate/
. - Use the links to add, list, update, and delete students.
Sample Output
When you add, list, update, and delete students, you should see the corresponding changes reflected in the listStudents.jsp
.
Conclusion
In this tutorial, we have successfully set up a JSP Servlet Hibernate web application using a MySQL database and the Student
entity. We configured the project dependencies, Hibernate, created an entity class, implemented servlets to handle CRUD operations, and demonstrated the use of JSPs to interact with the user. This guide provides a solid foundation for building a web application with JSP, Servlets, and Hibernate, allowing you to extend the application further as needed.
Comments
Post a Comment