Srikanth Technologies

Using Struts2 and Hibernate

In this blog I show a simple example to demonstrate how to use Struts2 with Hibernate. We use a simple registration page to take details from user and insert those details using Hibernate into Oracle database.

The blog covers the following :

In case you are not familiar with Struts2, please read my blog on Getting Started With Struts2 first and then the following.

Create a new web application using your favourite IDE. Make sure you create or modify the following files as shown below. Here I show where the files are to be placed in the web application. You need to place them in your IDE according to structure of your IDE. For example, all classes are to be placed in WEB-INF/classes in web application, but in NetBeans you need to place classes in Source Packages node (of course they are ultimately placed into WEB-INF/classes by NetBeans).

web.xml

Deployment descriptor, which is placed under WEB-INF, is used to configure filter related to Struts2 as follows:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>registeruser.jsp</welcome-file>
    </welcome-file-list>
</web-app>

hibernate.cfg.xml

Place hibernate configuration file classes folder under WEB-INF/classes as follows. It is configured to access Oracle10g with HR account. It also uses a single entity called User, which is in entities package.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping class="entities.User"/>
  </session-factory>
</hibernate-configuration>

struts.xml

Struts2 configuration file is used to specify the action classes and URLs to be invoked based on the string returned by execute() method in action class. Action class is placed in  WEB-INF/classes/actions  folder. However you can place action class in any package you like.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action  name="register" class="actions.RegisterAction">
            <result name="success">registercomplete.jsp</result>
            <result name="fail">registerfail.jsp</result>
        </action>
    </package>
</struts>

User class

User class is an entity that is mapped to Users table in Oracle database. Field userid is declared as Id and its value is automatically generated. We are using annotations to provide metadata regarding class and fields.

This is placed in WEB-INF/classes/entities folder.

package entities;

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 {
    @Id
    @GeneratedValue ( strategy =  GenerationType.AUTO)
    private int userid;
    private String email;
    private String password;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getUserid() {
        return userid;
    }
    
    public void setUserid(int userid) {
        this.userid = userid;
    }
}

HibernateUtil class

This class is used to create and return a single instance of SessionFactory. It uses AnnotationConfiguration class so that annotations are supported by Hibernate. Static initializer is used to create an object of SessionFactory and getSessionFactory() method to return it.

Place it in WEB-INF/classes/dao folder.

package dao;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

UserDAO class

This is used to access Hibernate from Struts2 action. It is based on Data Access Object design pattern.

This is placed in WEB-INF/classes/dao folder.


package dao;

import entities.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


public class UserDAO {

    public static boolean registerUser(User u) {

         SessionFactory sf = HibernateUtil.getSessionFactory();
         Transaction t = null;
         try  {
         Session s  = sf.openSession();
         t = s.beginTransaction(); // start a new transaction
         s.persist(u);
         t.commit();  // commit transaction  
         return true;
         }
         catch(Exception ex) {
             System.err.println("Error -->"  + ex.getMessage());
             if ( t!=null) t.rollback();  // rollback transaction on exception 
             return false;
         }
    }
}

RegisterAction class

This is the action class in Struts2. It uses UserDAO and User entity to insert a row into User table through Hibernate.

Place it in WEB-INF/classes/actions folder.

package actions;

import dao.UserDAO;
import entities.User;

public class RegisterAction {

    private String email,pwd;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public RegisterAction() {
    }

    public String execute() throws Exception {
        
        // create an object of User entity
        User u = new User();
        u.setEmail(email);
        u.setPassword(pwd);
        
        if ( UserDAO.registerUser(u))   // Access persistence tier through DAO
             return "success";
        else
            return "fail";
    }
}

registeruser.jsp

This is used to take information from user using struts2 user interface components.

This is placed in root directory of the application.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
    <head>
       <title>User Registration </title>
    </head>
    <body>
        <h2>User Registration</h2>
        <s:form action="register">
            <s:textfield name="email" label="Enter email address : "/>
            <s:password name="pwd" label="Enter your password : " />
            <s:submit value="Register" />
        </s:form>
    </body>
</html>

registercomplete.jsp and registerfail.jsp

These two JSPs are called depending on the result of the action. There JSPs are listed in struts.xml.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <body>
        <h1>Registration Completed Successfully!</h1>
    </body>
</html>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <body>
        <h1>Registration Failed!</h1>
        <a href="registeruser.jsp">Try Again </a>
    </body>
</html>

Directory Hierarchy

The following is the directory hierarchy of the entire web application.

struts2hibernate
    registeruser.jsp
    registercomplete.jsp
    registerfail.jsp
    WEB-INF
        web.xml
        classes
           hibernate.cfg.xml
           struts.xml
           entities
              User.class
           dao
              HibernateUtil.class
              UserDAO.class
           actions
              RegisterAction.class
        lib
            oracle driver
            struts2 related jar files
            Hibernate related jar files

In case you are using NetBeans IDE then at the time of creating web application select Hibernate and Struts2 (first you need to install Struts 2 plugin) options in Frameworks step. As a result NetBeans automatically includes all the necessary .jar files to project.

Deploy the application to any Java EE Web Container (such as Tomcat) and invoke registeruser.jsp from brower. Enter data into text boxes and click on submit button to insert a row into users table in Oracle database.


Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments


Posted By Sudarsan On 08-Mar-10 08:19:14 AM

Dear Sir,
I am new to this blog, but Ur posts are extremely useful to the beginners, I appreciate Ur subject and keep helping students for their bright future !!



Posted By Girish On 29-Mar-10 11:49:58 PM

Hi Sir,

Can you please show us with an example on how to implement N-Hibernate with ASP.NET ?



Posted By srinivasu namburi On 05-May-10 03:25:46 PM

This particular sample struts 2 integration with hibernate 3 annotation is really good. From this url i came to know that there no need of using hibernate.hbm.xml for mapping between persistence classes and DB tables with annotaion based approach. Sure i will try this example in my java IDE.



Posted By Vikram Raut On 19-Jun-10 07:51:01 PM

I am currently junior java developer and whenever I am in trouble I used ur site and get solution of problem by using ur site.
Thankig you forvever



Posted By Vijayakumar G S On 29-Sep-10 04:43:24 PM

Hi Sir, is there any way to integrate struts with hiberante with out using plugin?



Posted By raju On 29-Oct-10 01:32:38 PM

How to use business delegate with this example? Is it required?



Posted By Karuna On 08-Apr-11 12:54:49 PM

Dear Sir,
I am new to this blog, but ur post are really usefull to me and also for beginners !!!



Posted By Unknown On 13-Apr-11 11:41:58 PM

Your example are right on the money. thats a very good example for a beginner like me. Thanks a LOT !!!!



Posted By sunil On 28-Apr-11 12:33:20 PM

good



Posted By ANJU On 03-May-11 12:26:50 PM

GOOD boss
BUT I AM FED UP WITH CHANGING OF VERSION I LEARNT 1.1 NOW 2 CAME WHEN I WILL LEARN 2 STRUTS 3 WIL COME ARRE BHAI RUK JAO SALE



Posted By Lal singh On 21-Jul-11 08:29:57 PM

I am currently junior java developer and whenever I am in trouble I used ur site and get solution of problem by using ur site but i want one more solutiion for data retrive from database.
Thankig you forvever



Posted By Ashutosh Gangrade On 14-Sep-11 05:57:58 PM

Thank you very much. This code is really use full for me.



Posted By sumant pandey On 23-Oct-11 02:01:18 AM

coolll............very nice



Posted By thusar On 21-Mar-12 01:27:10 AM

great example



Posted By Ankit Gupta On 04-May-12 12:29:25 AM

Thankyou for your helpful blog, its my time to submit minor project and this really helped me alot!!

thanks alot! :)



Posted By mandar On 08-May-12 03:02:33 PM

I need one to many relation in hibernate annotation with struts2...



Posted By Rakesh On 29-Jul-13 04:36:57 PM

This Code is too good



Posted By Steve On 27-Jan-14 08:33:35 PM

I like your post, but what if you wanted to do this with hibernate in xml form only, how would you configure your .hbm file.

thanks,
Steve



Posted By Nandu On 04-Jul-14 02:36:03 PM

it is very nice sir. Sir, I want struts2 and hibernate code for image insert and retrieve on jsp page using struts2 and hibernate. Please provide me a code I'll send some students to you institute. If any student asking about course I'll send them directly to your institute.



Posted By pradeep On 15-Jan-16 06:12:29 PM

sir can give solution of the one to many example of hibernate using struts2



Posted By Yasas On 03-Mar-16 05:29:47 PM

There are different kind of tutorials here and there. but clearly I can say this one is the best for the beginners. thank u very much.