Hibernate Web Application Example

Web Application with Hibernate, JSP and Servlet using Eclipse


we are going to create a web application with hibernate. We will create Registration form and insert data in table. These data we will collect in servlet and finally insert these data into Database by using hibernate.
For creating the web application, we are using JSP for presentation logic, Servlet class for controller layer and DAO class for database access codes.

Tools and Technologies:

·         JDK 1.8
·         Hibernate 3.6.3.Final
·         Eclipse Luna
·         MySQL 5.5.
·         Tomcat 7.0

Follow the steps mentioned below to create this example.

Step 1 : Create Dynamic Web Project :

Open eclipse IDE,and go to File -> New -> Project -> and select Dynamic Web Project, specify the project name as HibernateWebApp and click on next -> finish .

Step 2 : Add Jar files for hibernate and mysql :

Copy all the jar files as shown below inside lib folder of the project.

Step 3 : Creating web pages :

Now let us create register.jsp file inside Web-Content folder of your project. This is a simple form where user can provide his/her detail.
Right Click on Web-Content then New -> JSP File and provide the name of JSP file as register.jsp and click Finish.

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Form</title>
</head>
<body>
       <h1>Registration Form</h1>
       <form action="register" method="post">
              <table cellpadding="3pt">
                     <tr>
                           <td>User Name :</td>
                           <td><input type="text" name="userName" size="30" /></td>
                     </tr>
                     <tr>
                           <td>Password :</td>
                           <td><input type="password" name="password1" size="30" /></td>
                     </tr>

                     <tr>
                           <td>Confirm Password :</td>
                           <td><input type="password" name="password2" size="30" /></td>
                     </tr>
                     <tr>
                           <td>email :</td>
                           <td><input type="text" name="email" size="30" /></td>
                     </tr>
                     <tr>
                           <td>Phone :</td>
                           <td><input type="text" name="phone" size="30" /></td>
                     </tr>
                     <tr>
                           <td>City :</td>
                           <td><input type="text" name="city" size="30" /></td>
                     </tr>
              </table>
              <p />
              <input type="submit" value="Register" />
       </form>
</body>
</html>

Step 4 : Creating Java Classes :

Create a package com.jwt.hibernate.controller and create a java class UserControllerServlet in this package and add following code in this class.
UserControllerServlet.java
package com.jwt.hibernate.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jwt.hibernate.dao.UserDAO;

public class UserControllerServlet extends HttpServlet {
           
            private static final long serialVersionUID = 1L;

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

                        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 {
                                    UserDAO userDAO = new UserDAO();
                                    userDAO.addUserDetails(userName, password, email, phone, city);
                                    response.sendRedirect("Success");
                        } catch (Exception e) {

                                    e.printStackTrace();
                        }

            }
}

Above class is controller class for our application. In this class we are collecting the data from user and storing the data by calling UserDAO class addUserDetails method. If the database insertion is successful request will be forwarded to Success.java Servlet class.
User.java
This is a simple bean class representing the Persistent class in hibernate.
Create a package com.jwt.hibernate.bean,in this package create java class User.java and add following code in this class.

package com.jwt.hibernate.bean;

public class User {
       private int id;
       private String userName;
       private String password1;
       private String email;
       private String phone;
       private String city;

       //generate getters & setters
}

UserDAO.java
This is DAO class. In this class we have implemented addUserDetails() method where we are adding the user details to database by using hibernate.
Create a package com.jwt.hibernate.dao,in this package create java class UserDAO.java and add following code in this class.

package com.jwt.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jwt.hibernate.bean.User;

public class UserDAO {

            public void addUserDetails(String userName, String password, String email,
                                    String phone, String city) {
                        try {
                                    // 1. configuring hibernate
                                    Configuration configuration = new Configuration().configure();

                                    // 2. create sessionfactory
                                    SessionFactory sessionFactory = configuration.buildSessionFactory();

                                    // 3. Get Session object
                                    Session session = sessionFactory.openSession();

                                    // 4. Starting Transaction
                                    Transaction transaction = session.beginTransaction();
                                    User user = new User();
                                    user.setUserName(userName);
                                    user.setPassword1(password);
                                    user.setEmail(email);
                                    user.setCity(city);
                                    user.setPhone(phone);
                                    session.save(user);
                                    transaction.commit();
                                    System.out.println("\n\n Details Added \n");

                        } catch (HibernateException e) {
                                    System.out.println(e.getMessage());
                                    System.out.println("error");
                        }
            }
}

Success.java
User will be redirected to this class after successful insertion of data.

package com.jwt.hibernate.controller;

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 Success extends HttpServlet {

            protected void doGet(HttpServletRequest request,
                                    HttpServletResponse response) throws ServletException, IOException {
                        PrintWriter writer = response.getWriter();

                        writer.println("<html>" + "<body bgcolor='cyan'>" + "<center>"
                                                + "Details Added Successfully" + "</center>" + "</body>"
                                                + "</html>");
            }

}

Step 5 : Create the mapping file :

Mapping file maps the User class with the table of the database.
Right click on com.jwt.hibernate.bean then navigate to New -> Other -> General -> Next and provide the name of file as user.hbm.xml and click on finish.After creating user.hbm.xml add following code in this file.
user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
       <class name="com.jwt.hibernate.bean.User" table="USER">
              <id column="ID" name="id" type="java.lang.Integer" />
              <property column="USER_NAME" name="userName" type="java.lang.String" />
              <property column="PASSWORD" name="password1" type="string" />
              <property column="EMAIL" name="email" 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>

Step 6 : Create the Configuration file :

The configuration file contains informations about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml .Configuration file must be in classpath of your Project.Place this file in src of your project by default it will added to classpath of your project.
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
       <session-factory>
              <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
              <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
              <property name="hibernate.connection.username">root</property>
              <property name="hibernate.connection.password"></property>
              <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
              <property name="show_sql">true</property>
              <property name="format_sql">true</property>
              <property name="hbm2ddl.auto">create </property>
              <mapping resource="com/jwt/hibernate/bean/user.hbm.xml" />
       </session-factory>
</hibernate-configuration>

Step 7: Create web.xml file :

Create web.xml file inside WEB-INF directory of project.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       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.jwt.hibernate.controller.UserControllerServlet</servlet-class>
       </servlet>
       <servlet>
              <display-name>Success</display-name>
              <servlet-name>Success</servlet-name>
              <servlet-class>com.jwt.hibernate.controller.Success</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>

Directory structure of the project :


Directory Structure of the project is given bellow.



Run the Application :

To run the hibernate web application, right click on the project then Run as -> Run On Server select Tomcat -> Next ->Finish.

Output in Browser :


 After click on Register




Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes