Hibernate Registration Form Example with JSP, Servlet, MySQL

In this article, we will create a User Registration project using JSP, Servlet, Hibernate Framework, and MySQL database.

What we will develop?

In this example, we will develop the below flow:
1. Creating a User Registration form using JSP
2. Submit the User Registration form with a POST request
3. After form submission the corresponding servlet will get called
4. UserController class handles all the request parameters and sends a request to the UserDao class to save this data to the database.
 
The below diagram shows the User Registration JSP page:

1. Create a Dynamic Web Project in Eclipse IDE

To create a new dynamic Web project in Eclipse:
1. On the main menu select File > New > Project...
2. In the upcoming wizard choose Web > Dynamic Web Project.


3. Click Next.
4. Enter project name as "registration-jsp-servlet-hibernate-example";
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version. 

2. Add Jar Dependencies

You can get these jar dependencies from the GitHub repository (the link given at the end of this tutorial). Add the latest release of the below jar files to the lib folder:

3. Project Structure

Create project structure or packaging structure as per the below screenshot:

4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Next, create a users table using below DDL script:
CREATE TABLE `users` (
   `id` int(3) NOT NULL,
   `first_name` varchar(20) DEFAULT NULL,
   `last_name` varchar(20) DEFAULT NULL,
   `username` varchar(250) DEFAULT NULL,
   `password` varchar(20) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SELECT * FROM mysql_database.employee; 

5. Create a JPA Entity - User.java

Next, create User JPA Entity class and add the following content to it:
package net.javaguides.hibernate.model;

import java.io.Serializable;

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

@Entity
@Table(name = "users")
public class User implements Serializable {
    private static final long serialVersionUID = 1 L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "user_name")
    private String username;

    @Column(name = "password")
    private String password;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    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;
    }
}

6. Create UserDao to Save Registered User into Database

Let's create a UserDao class and add the saveUser() method to save Users into the users table in a database using Hibernate.

Here’s the full source code of the UserDao:
package net.javaguides.hibernate.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.javaguides.hibernate.model.User;
import net.javaguides.hibernate.util.HibernateUtil;


public class UserDao {

    public void saveUser(User user) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            transaction = session.beginTransaction();
            // save the student object
            session.save(user);
            // commit transaction
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

7. Hibernate Java-Based Configuration

package net.javaguides.hibernate.util;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;

import net.javaguides.hibernate.model.User;

/**
 * Java based configuration
 * @author ramesh Fadatare
 *
 */
public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();

                // Hibernate settings equivalent to hibernate.cfg.xml's properties
                Properties settings = new Properties();
                settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
                settings.put(Environment.URL, "jdbc:mysql://localhost:3306/demo?useSSL=false");
                settings.put(Environment.USER, "root");
                settings.put(Environment.PASS, "root");
                settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");

                settings.put(Environment.SHOW_SQL, "true");

                settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");

                settings.put(Environment.HBM2DDL_AUTO, "create-drop");

                configuration.setProperties(settings);
                configuration.addAnnotatedClass(User.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
                System.out.println("Hibernate Java Config serviceRegistry created");
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                return sessionFactory;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
}
Let's understand the above code:
Singleton SessionFactory: The class provides a Singleton pattern for a SessionFactory object. The SessionFactory is responsible for creating Hibernate Session objects, which are used to interact with the database. By using a Singleton pattern, the class ensures that only one SessionFactory instance is created throughout the application's lifecycle. 

Database Configuration: Inside the getSessionFactory method, database connection properties are configured using a Properties object. These properties include the JDBC driver class, connection URL, username, password, dialect for MySQL, and other Hibernate-specific settings such as SHOW_SQL and HBM2DDL_AUTO. 

Annotated Class Configuration: The method configuration.addAnnotatedClass(User.class) is used to add the User entity class to the Hibernate configuration. This allows Hibernate to recognize the User class and map it to the corresponding database table. 

Service Registry Building: A ServiceRegistry object is created using the StandardServiceRegistryBuilder class and the properties from the configuration object. The ServiceRegistry is used by Hibernate to manage services needed for database communication. 

SessionFactory Initialization: Finally, the SessionFactory is initialized using the configuration and service registry with configuration.buildSessionFactory(serviceRegistry). If an exception occurs during this initialization, it is caught and printed, and the method returns the existing sessionFactory object, which may be null if this is the first time the method has been called.

8. Create a UserController.java

Now, let's create UserController that acts as a page controller to handle all requests from the client:
package net.javaguides.hibernate.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 net.javaguides.hibernate.dao.UserDao;
import net.javaguides.hibernate.model.User;

/**
 * @email Ramesh Fadatare
 */

@WebServlet("/register")
public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1 L;
    private UserDao userDao;

    public void init() {
        userDao = new UserDao();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        register(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.sendRedirect("register.jsp");
    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setUsername(username);
        user.setPassword(password);

        userDao.saveUser(user);

        RequestDispatcher dispatcher = request.getRequestDispatcher("register-success.jsp");
        dispatcher.forward(request, response);
    }
}

9. Create a View - register.jsp

Let's design a user registration HTML form with the following fields:
  • firstName
  • lastName
  • username
  • password
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
 integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
 crossorigin="anonymous">
</head>

</head>
<body>
 <div class="container">
 <div class="row text-center" style="color: tomato;">
  <h2>User Registration with JSP, Servlet and Hibernate</h2>
 </div>
 <hr>
  <div class="row col-md-10 col-md-offset-3"> 
   
   <div class="card card-body">
   
    <h2>User Register Form</h2>
    <div class="col-md-8 col-md-offset-3">

     <form action="<%=request.getContextPath()%>/register" method="post">

      <div class="form-group">
       <label for="uname">First Name:</label> <input type="text"
        class="form-control" id="uname" placeholder="First Name"
        name="firstName" required>
      </div>

      <div class="form-group">
       <label for="uname">Last Name:</label> <input type="text"
        class="form-control" id="uname" placeholder="last Name"
        name="lastName" required>
      </div>

      <div class="form-group">
       <label for="uname">User Name:</label> <input type="text"
        class="form-control" id="username" placeholder="User Name"
        name="username" required>
      </div>

      <div class="form-group">
       <label for="uname">Password:</label> <input type="password"
        class="form-control" id="password" placeholder="Password"
        name="password" required>
      </div>

      <button type="submit" class="btn btn-primary">Submit</button>

     </form>
    </div>
   </div>
  </div>
 </div>
</body>
</html>

10. Create a View - register-success.jsp

Let's create a register-success.jsp page and add the following code to it:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
 integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
 crossorigin="anonymous">
</head>

</head>
<body>
 <div class="container">
  <div class="row col-md-10 col-md-offset-3">
   <div class="card card-body">
    <h1>User successfully registered!</h1>
   </div>
  </div>
 </div>
</body>
</html>

11. Run the Application and Demo

Deploy this web application in the Tomcat server in Eclipse IDE.
Type the following URL in your web browser to access this application: http://localhost:8080/registration-jsp-servlet-hibernate-example/register.

User Registration Form:

User Register Success Page:

Conclusion 

This tutorial provided a step-by-step guide to creating a registration form using JSP, Servlet, Hibernate, and MySQL. Now, when a user fills out the registration form, the information is saved in the MySQL database using Hibernate. Make sure you handle any necessary error checking, validation, and security measures (e.g., hashing passwords) in a real-world application. 

You can download the source code of this tutorial from my GitHub repository.

Comments

  1. why in my project, on this line in UserDao.java
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
    error incompatible types? can you solve it?, i'm using Netbeans IDE

    ReplyDelete

Post a Comment

Leave Comment