User
entity for this example. The focus will be on setting up the environment and demonstrating the login functionality.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 (
User
). - Create JSPs for the login interface.
- Implement Servlets for handling login requests.
- 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>login-example</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 User
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 User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
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 the login form.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<form action="loginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
<p>${message}</p>
</body>
</html>
Create a welcome.jsp
to display a welcome message upon successful login.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, ${username}!</h1>
</body>
</html>
Explanation:
index.jsp
provides a form to collect user credentials.welcome.jsp
displays a welcome message for the logged-in user.
Step 5: Implement Servlet for Handling Login Requests
Create a servlet named LoginServlet
to handle login requests.
5.1 Create LoginServlet
package com.example.servlet;
import com.example.entity.User;
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 java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Session session = HibernateUtil.getSessionFactory().openSession();
User user = (User) session.createQuery("FROM User WHERE username = :username AND password = :password")
.setParameter("username", username)
.setParameter("password", password)
.uniqueResult();
session.close();
if (user != null) {
request.setAttribute("username", user.getUsername());
request.getRequestDispatcher("welcome.jsp").forward(request, response);
} else {
request.setAttribute("message", "Invalid username or password");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
Explanation:
- The
LoginServlet
class handles POST requests to authenticate the user using Hibernate and redirect to the appropriate JSP page based on the authentication result.
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/login-example/
. - Use the login form to enter user credentials and test the login functionality.
Sample Output
When you log in with valid credentials, you should be redirected to welcome.jsp
displaying a welcome message. If the credentials are invalid, you should see an error message on the index.jsp
.
Conclusion
In this tutorial, we have successfully set up a JSP Servlet Hibernate web application using a MySQL database and the User
entity. We configured the project dependencies, Hibernate, created an entity class, implemented a servlet to handle login requests, and demonstrated the use of JSPs to create a login interface. 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