Hibernate Registration Form Example with JSP, Servlet, MySQL

In this article, we will build a simple User Registration module using JSP, Servlet, Hibernate Framework, and MySQL database.

In this example, we will develop below flow:
1. Creating a User Registration form using JSP
2. Submit User Registration form with a POST request and URL - /register
3. After form submission corresponding servlet will get called - UserController.java
4. UserController class handles all the request parameters and sends a request to the UserDao class to save this data to the database.
Below diagram shows the User Registration JSP page:
Let me list out the tools and technologies that I have used to develop this application.

Tools and technologies used

  • JSP - 2.2 +
  • Hibernate - 5+
  • IDE - STS/Eclipse Neon.3
  • JDK - 1.8 or later
  • Apache Tomcat - 8.5
  • JSTL - 1.2.1
  • Servlet API - 2.5
  • MySQL - mysql-connector-java-8.0.13.jar

Development Steps

  1. Create an Eclipse Dynamic Web Project
  2. Add Dependencies
  3. Project Structure
  4. MySQL Database Setup
  5. Create a JPA Entity - User.java
  6. Create a UserDao.java
  7. Create a UserController.java
  8. Hibernate Java Based Configuration
  9. Create a register.jsp
  10. Create a register-success.jsp
  11. Demo

1. Create an Eclipse Dynamic Web Project

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 Dependencies

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

3. Project Structure

Standard project structure for your reference -

4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Now, 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

Let's create a User persistent class that is mapped to a database table - users.
A simple Persistent class should follow some rules:
  • A no-arg constructor: It is recommended that you have a default constructor at least package visibility so that hibernate can create the instance of the Persistent class by newInstance() method.
  • Provide an identifier property: It is better to assign an attribute as id. This attribute behaves as a primary key in a database.
  • Declare getter and setter methods: The Hibernate recognizes the method by getter and setter method names by default.
  • Prefer non-final class: Hibernate uses the concept of proxies, which depends on the persistent class. The application programmer will not be able to use proxies for lazy association fetching.
Here is the User JPA Entity class:
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 using Hibernate SessionFactory

Let's create a UserDao class which is a Data Access Layer (DAO) class that provides saveUser() method to save Users into 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;
    }
}
  • ServiceRegistry holds the services that Hibernate will need during bootstrapping and at runtime.
  • StandardServiceRegistryBuilder - Builder for standard ServiceRegistry instances.
  • HibernateUtil - This is the helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory. The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object. 

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 register.jsp

Let's design 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 register-success.jsp

Let's create a register-success.jsp page:
<%@ 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 Application and Demo

Deploy this web application in 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:

Download source code at https://github.com/RameshMF/Hibernate-ORM-Tutorials/tree/master/registration-jsp-servlet-hibernate-example

Comments