Open In App

Hibernate – Web Application

Last Updated : 06 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes.

Tools and Technologies used in this project:

  • JDK 1.6+ onwards
  • Hibernate 3.6.3.Final or next versions
  • Eclipse
  • MySQL 5.5. or next versions
  • Tomcat

As Hibernate – Web Application is going to get prepared, the project is going to get prepared as a dynamic web project. Following jars need to be placed in the WEB-INF/lib folder

Front-end JSP page that gets input from user

register.jsp

HTML




<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Form</title>
</head>
<style>
body {
    font-family: Verdana, Geneva, sans-serif;
    font-size: 14px;
    background: #006400;
}
.clearfix {
    &:after {
        content: "";
        display: block;
        clear: both;
        visibility: hidden;
        height: 0;
    }
}
.form_wrapper {
    background: #fff;
    width: 600px;
    max-width: 100%;
    box-sizing: border-box;
    padding: 25px;
    margin: 8% auto 0;
    position: relative;
    z-index: 1;
    border-top: 5px solid $yellow;
    -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    -webkit-transform-origin: 50% 0%;
    transform-origin: 50% 0%;
    -webkit-transform: scale3d(1, 1, 1);
    transform: scale3d(1, 1, 1);
    -webkit-transition: none;
    transition: none;
    -webkit-animation: expand 0.8s 0.6s ease-out forwards;
    animation: expand 0.8s 0.6s ease-out forwards;
    opacity: 0;
    h2 {
        font-size: 1.5em;
        line-height: 1.5em;
        margin: 0;
    }
    .title_container {
        text-align: center;
        padding-bottom: 15px;
    }
    h3 {
        font-size: 1.1em;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
    }
    label {
        font-size: 12px;
    }
    .row {
        margin: 10px -15px;
        >div {
            padding: 0 15px;
            box-sizing: border-box;
        }
    }
    .col_half {
        width: 50%;
        float: left;
    }
    .input_field {
        position: relative;
        margin-bottom: 20px;
        -webkit-animation: bounce 0.6s ease-out;
           animation: bounce 0.6s ease-out;
        >span {
            position: absolute;
            left: 0;
            top: 0;
            color: #333;
            height: 100%;
            border-right: 1px solid $grey;
            text-align: center;
            width: 30px;
            >i {
                padding-top: 10px;
            }
        }
    }
    .textarea_field {
        >span {
            >i {
                padding-top: 10px;
            }
        }
    }
    input {
    &[type="text"], &[type="email"], &[type="password"] {
      width: 100%;
      padding: 8px 10px 9px 35px;
      height: 35px;
      border: 1px solid $grey;
      box-sizing: border-box;
      outline: none;
      -webkit-transition: all 0.30s ease-in-out;
      -moz-transition: all 0.30s ease-in-out;
      -ms-transition: all 0.30s ease-in-out;
      transition: all 0.30s ease-in-out;
    }
    &[type="text"]:hover, &[type="email"]:hover, &[type="password"]:hover {
      background: #fafafa;
    }
    &[type="text"]:focus, &[type="email"]:focus, &[type="password"]:focus {
      -webkit-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      -moz-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);
      border: 1px solid $yellow;
      background: #fafafa;
    }
    &[type="submit"] {
        background: $yellow;
        height: 35px;
        line-height: 35px;
        width: 100%;
        border: none;
        outline: none;
        cursor: pointer;
        color: #fff;
        font-size: 1.1em;
        margin-bottom: 10px;
        -webkit-transition: all 0.30s ease-in-out;
        -moz-transition: all 0.30s ease-in-out;
        -ms-transition: all 0.30s ease-in-out;
        transition: all 0.30s ease-in-out;
        &:hover {
            background: darken($yellow,7%);
        }
        &:focus {
            background: darken($yellow,7%);
        }
    }   
    &[type="checkbox"], &[type="radio"] {
      border: 0;
      clip: rect(0 0 0 0);
      height: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1px;
    }
  }
}
.form_container {
    .row {
        .col_half.last {
            border-left: 1px solid $grey;
        }
    }
}
 
@-webkit-keyframes check {
  0% { height: 0; width: 0; }
  25% { height: 0; width: 7px; }
  50% { height: 20px; width: 7px; }
}
 
@keyframes check {
  0% { height: 0; width: 0; }
  25% { height: 0; width: 7px; }
  50% { height: 20px; width: 7px; }
}
 
@-webkit-keyframes expand {
    0% { -webkit-transform: scale3d(1,0,1); opacity:0; }
    25% { -webkit-transform: scale3d(1,1.2,1); }
    50% { -webkit-transform: scale3d(1,0.85,1); }
    75% { -webkit-transform: scale3d(1,1.05,1); }
    100% { -webkit-transform: scale3d(1,1,1);  opacity:1; }
}
 
@keyframes expand {
    0% { -webkit-transform: scale3d(1,0,1); transform: scale3d(1,0,1);  opacity:0; }
    25% { -webkit-transform: scale3d(1,1.2,1); transform: scale3d(1,1.2,1); }
    50% { -webkit-transform: scale3d(1,0.85,1); transform: scale3d(1,0.85,1); }
    75% { -webkit-transform: scale3d(1,1.05,1); transform: scale3d(1,1.05,1); }
    100% { -webkit-transform: scale3d(1,1,1); transform: scale3d(1,1,1);  opacity:1; }
}
 
 
@-webkit-keyframes bounce {
    0% { -webkit-transform: translate3d(0,-25px,0); opacity:0; }
    25% { -webkit-transform: translate3d(0,10px,0); }
    50% { -webkit-transform: translate3d(0,-6px,0); }
    75% { -webkit-transform: translate3d(0,2px,0); }
    100% { -webkit-transform: translate3d(0,0,0); opacity: 1; }
}
 
@keyframes bounce {
    0% { -webkit-transform: translate3d(0,-25px,0); transform: translate3d(0,-25px,0); opacity:0; }
    25% { -webkit-transform: translate3d(0,10px,0); transform: translate3d(0,10px,0); }
    50% { -webkit-transform: translate3d(0,-6px,0); transform: translate3d(0,-6px,0); }
    75% { -webkit-transform: translate3d(0,2px,0); transform: translate3d(0,2px,0); }
    100% { -webkit-transform: translate3d(0,0,0); transform: translate3d(0,0,0); opacity: 1; }
}
@media (max-width: 600px) {
    .form_wrapper {
        .col_half {
            width: 100%;
            float: none;
        }
    }
    .bottom_row {
        .col_half {
            width: 50%;
            float: left;
        }
    }
 
}
</style>
<body>
<div class="form_wrapper">
  <div class="form_container">
    <div class="title_container">
    <h1>GeekUser Registration Form</h1>
    <form action="register" method="post">
        <table cellpadding="3pt">
            <tr>
                <td>User Name :</td>
                <td><input type="text" name="userName" size="50" /></td>
            </tr>
            <tr>
                <td>Password :</td>
                <td><input type="password" name="password1" size="50" /></td>
            </tr>
 
            <tr>
                <td>Confirm Password :</td>
                <td><input type="password" name="password2" size="50" /></td>
            </tr>
            <tr>
                <td>email :</td>
                <td><input type="text" name="email" size="50" /></td>
            </tr>
            <tr>
                <td>Phone :</td>
                <td><input type="text" name="phone" size="50" /></td>
            </tr>
            <tr>
                <td>City :</td>
                <td><input type="text" name="city" size="50" /></td>
            </tr>
        </table>
        <p />
        <input type="submit" value="Register" />
    </form>
    </div>
    </div>
    </div>
</body>
</html>


 
 

Output of this page:

 

Output

 

Creating Java class namely a POJO class, a controller class, DAO class

 

Controller class > GeekUserControllerServlet.java

 

Java




import com.gfg.hibernate.dao.GeekUserDAO;
 
public class GeekUserControllerServlet extends HttpServlet {
     
    private static final long serialVersionUID = 1L;
 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
        // From register.jsp, the controls
        // are passed to this controller servlet
        String userName = request.getParameter("userName");
        String password = request.getParameter("password1");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String city = request.getParameter("city");
        HttpSession session = request.getSession(true);
        try {
            GeekUserDAO userDAO = new GeekUserDAO();
            // Via DAO class addGeekUser method,
            // the data is inserted into the table
            userDAO.addGeekUser(userName, password, email, phone, city);
            // After that it is redirected to the success page
            response.sendRedirect("Success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


 
 

Let us see DAO class > GeekUserDAO.java

 

Java




import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.gfg.hibernate.bean.GeekUser;
public class GeekUserDAO {   
    // Method to insert GeekUser in the database
    public Integer addGeekUser(String userName,
     String password,
     String email,
     String phone,
     String city) {
         SessionFactory sessionFactory;
            try {
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            GeekUser geekUser = new GeekUser(userName, password, email,phone,city);
            employeeID = (Integer) session.save(geekUser);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }
}


 
 

Via DAO method, the details are getting inserted into the database. We see that via GeekUser bean class, the data is sent. Let us see the POJO class

 

POJO class > GeekUser.java

 

Java




public class GeekUser {
    // each and every attribute should have
    // the respective column in the database
    private int id;
    private String geekUserName;
    private String password;
    private String geekEmail;
    private String phone;
    private String city;   
    public GeekUser() {
         
    }
    // parameterized constructors are
    // necessary to carry the details
    public GeekUser(String userName,
     String password,
     String email,
     String phone,
     String city) {
        this.geekUserName = userName;
        this.password = password;
        this.geekEmail = email;
        this.phone = phone;
        this.city = city;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getGeekUserName() {
        return geekUserName;
    }
 
    public void setGeekUserName(String userName) {
        this.geekUserName = userName;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password1) {
        this.password = password1;
    }
 
    public String getGeekEmail() {
        return geekEmail;
    }
 
    public void setGeekEmail(String email) {
        this.geekEmail = email;
    }
 
    public String getPhone() {
        return phone;
    }
 
    public void setPhone(String phone) {
        this.phone = phone;
    }
 
    public String getCity() {
        return city;
    }
 
    public void setCity(String city) {
        this.city = city;
    }
 
}


 
 

Once the details are added successfully, it is redirected to SuccessPage.java

 

Java




import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class SuccessPage extends HttpServlet {
 
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
 
        writer.println("<html>" + "<body bgcolor='#006400'>" + "<center><h3><font color='white'>"
                + "GeekUser details are added successfully via Hibernate. " + "</font></h3></center>" + "</body>"
                + "</html>");
    }
 
}


Let us see the output of the flow:

Let us check the table data also parallelly

Hibernate makes the process very easier.

A bean class(Here it is GeekUser.java) is required. Each and every attribute of a bean class has to be mapped in a hbm(hibernate mapping file) file. It is an XML file where each and every attribute are mapped perfectly to the table in the database.

geekuser.hbm.xml  (Mapping file which maps bean (POJO) class attributes to corresponding table)

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping>
    <!-- GeekUser bean class is mapped to GEEKUSER table -->
    <class name="com.gfg.hibernate.bean.GeekUser" table="GEEKUSER">
        <!-- This makes id attribute to be of int datatype and Primary Key -->
        <id column="id" name="id" type="int">
            <generator class="native"/>
           </id>
        <!-- geekUserName,password,geekEmail,phone and city
             are the other attributes that need to be mapped -->
        <property column="geekUserName" name="geekUserName" type="java.lang.String" />
        <property column="password" name="password" type="string" />
        <property column="geekEmail" name="geekEmail" type="java.lang.String" />
        <property column="phone" name="phone" type="java.lang.String" />
        <property column="city" name="city" type="java.lang.String" />
    </class>
</hibernate-mapping>


Main hibernate configuration file > hibernate.cfg.xml

XML




<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <!-- As we are going to connect with mysql, this is required -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/geeksforgeeks</property>
        <property name="hibernate.connection.username">root</property>
        <!-- Provide your correct password here -->
        <property name="hibernate.connection.password">XXXX</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <!-- In order to show the SQL query in console, this is required -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hbm2ddl.auto">create </property>
        <!-- Specification of exact hibernate mapping file need to be specified -->
        <mapping resource="com/gfg/hibernate/bean/geekuser.hbm.xml" />
    </session-factory>
</hibernate-configuration>


As this is the web application, let us see web.xml as well which will help for the flow of data from jsp to servlet.

XML




<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>HibernateWebApp</display-name>
    <servlet>
        <display-name>User</display-name>
        <servlet-name>User</servlet-name>
        <servlet-class>com.gfg.hibernate.controller.GeekUserControllerServlet</servlet-class>
    </servlet>
    <servlet>
        <display-name>Success</display-name>
        <servlet-name>Success</servlet-name>
        <servlet-class>com.gfg.hibernate.controller.SuccessPage</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>User</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Success</servlet-name>
        <url-pattern>/Success</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>register.jsp</welcome-file>
    </welcome-file-list>
</web-app>


 
 

Video file for the project:

 

Conclusion

 

In this tutorial, we have seen that by using the very nice feature of hibernate, data are getting inserted into the database table in an easier way. One more important thing is like for any kind of database, this works. If we are changing a different database, we need to change hibernate.cfg.xml to support it

 

XML




<!-- for sql server -->
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="hibernate.connection.driver_class">com.microsoft.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc.Microsoft://localhost/<dbname></property>
        <property name="hibernate.connection.username">root</property>
          <!-- Need to change proper password -->
        <property name="hibernate.connection.password">****</property>
    </session-factory>
</hibernate-configuration>
  <!-- for oracle -->
  <session-factory>
    <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:dbname</property>
    <property name="connection.username">user</property>
    <property name="connection.password">***</property>
    <property name="dialect">org.hibernate.dialect.Oracle8iDialect</property>    
    <property name="show_sql">true</property>     
  </session-factory>
  <!-- Similarly for other database, it has to be specified


 
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads