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
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.
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
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;
}
}
8. Create a UserController.java
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
- 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
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.
why in my project, on this line in UserDao.java
ReplyDeletetry (Session session = HibernateUtil.getSessionFactory().openSession()) {
error incompatible types? can you solve it?, i'm using Netbeans IDE