Integrating Struts 2.0 applications with Hibernate

Struts 2.0 is one of the popularly used Presentation tier framework for Java web Applications.It is based on the WebWork2 technology.Struts 2.0 framework implements MVC 2 architecture by centralizing the control using a Front Controller strategy. The extensible and flexible nature of Struts 2.0 makes it the favourite choice of Java web developers. The major features of Struts 2.0 are user interface tags, Interceptor, result and validation.

also read:

A strong persistence framework is critical to the success and scalability of any application that we develop. Today we have a lot of data access frameworks like Hibernate, JDBC, JPAs, etc available in the market. Sturts can be integrated easily with any of these popularly used data access frameworks.

This article demonstrates the integration of Struts 2.0 applications with the Hibernate. The concept is explained with the help of a sample application. There are pluggins also available for integrating Struts 2.0 with Hibernate. The sample application used in this articile does not use any pluggins.

The author asuumes readers of this article have basic knowledge of Struts 2.0 and Hibernate.If you are beginner in learning Struts and hibernate, please read Introduction to Struts 2.0 and Introduction to Hibernate. The sample is created in NetBens IDE. Sample project struture is displayed in the next section.

Project Structure

This application which is discussed here stores the registration details of an employee to an Oracle DB table using struts 2 and hibernate.Includ the hibernate jar files and struts 2.0 jar files to the project class path. Since we are using Oraccle we need to load the classes12.jar/odbc5.jar also to the class path.

Create the domain model as below.This class will be used as the hibernate model object.Hence we need to have the hibernate mapping files created for this as listed in the next section.

The same is used to push the form data to the valuestack.ValueStack, as you know already , is ,one of the powerful features of Struts 2.ValueStack can be defined as a storage structure where the data associated with the current request is stored.

The properties of this bean is directly accessible from the JSP pages using OGNL expresion language.

Listing 1.
public class Employee {
    private int empno;
    private String name;
    private String jobtitle;
    private String unit;//business unit  - Retail,Testing, etc
    private String technology;//current working technology
	// getter  & setter methods

Struts 2.0 Action Class

As you are already aware of , Struts 2 do not have the ActionForm concept. But those of you ,who would like to use such a feature in Struts 2, they can create a POJO that holds the form data in its properties and then create an Action class that implements the ModelDriven interface. This is what we have done in the sample described here.

Please note that when you implement ModelDriven interface, you need to get the model object using the getModel() method. The Preparable interface is implemented here so that the action class can prepare itself. If you don’t have anything to prepare, there’s no reason to implement Preparable. Here we are initializing the instance of the Employee object with the prepare() method of the Preparable interface.

Listing 2 : Model Driven Action class –
package com.myaction;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Registration extends ActionSupport implements ModelDriven, Preparable {

    Employee employee;
    SessionFactory sessionFactory = null;
    Session session = null;

    public String execute() {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            transaction .commit();
            System.out.println("Record Inserted Successfully");
        } catch (HibernateException hibernateException) {
            return "ERROR";
        return "SUCCESS";

    public Employee getModel() {
        return employee;
    public void prepare() throws Exception {
        employee = new Employee();

In this action class we are obtaining the SessionFactory instance from the hibernate configuration. Once the SessionFactory instance is obtained, you can create the Session object and invoke the necessary methods for insertion / updation of the records in the table.

JSP Pages

We use three JSP pages in this application. The first one is the index.jsp page that accepts the registration details of the employee. Upon submiting this form, the action class’ execute method is invoked and data is strored in the database. Success.jsp(Listed next) will be shown to the user upon successful insertion of the data.

If an error occurs during insertion , Error.jsp is displayed.

Listing 3 :index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<%@taglib uri="/struts-tags"  prefix="s"%>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
            <!-- <img src="PDT_TVM_SMall.JPG"/> -->
            <h1>Registration Form</h1>
            <s:form action="Registration">
                <table bgcolor="pink">
                            <s:textfield name="empno" label=" Employee Id " value="" />
                            <s:textfield name="name" label=" Name" />
                            <s:textfield name="jobtitle" label=" Job Title " />
                            <s:combobox label=" Business Unit " name="unit"
                                        headerValue="--- Please Select ---"
                                        list="{'Retail','HR','Quality','R&D','Testing','Facilities'}" />
                            <s:combobox label=" Current Technology Area" name="technology"
                                        headerValue="--- Please Select ---"
                                        list="{'Java','J2EE','.NET','Main Frame','Others'}"/>
                        <td colspan="0"><s:submit label="Register"/></td>
Listing 4 : Success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" import="com.myaction.Employee"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<%@taglib prefix="s"  uri="/struts-tags"%>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
            <br>  <br>  <br>  <br>
            <h1 style="color:chocolate"> <s:property value="name"/> registered successfully !!</h1>
Listing 5 : Error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" errorPage="Error.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Error Page</title>
        <h1>Some Error Occurred !!  </h1>

Oracle Database table structure

Listing 6 : web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Hibernate and Struts 2 configuration files

Listing 7 : Struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    <!-- Configuration for the default package. -->
     <package name="default" extends="struts-default">
        <action name="Registration" class="com.myaction.Registration">
            <result name="SUCCESS">/Success.jsp</result>
             <result name="ERROR">/Error.jsp</result>
Listing 8 : hibernate.cfg.xml – Hibernate configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
        <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">password</property>
        <property name="">update</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="Employee.hbm.xml"/>
Listing 9 : Employee.hbm.xml – hibernate mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  <class name="com.myaction.Employee" table="StrutsHibEmployee">
    <id column="EMPNO" name="empno" type="int">
      <generator class="assigned"/>
    <property column="EMPNAME" name="name" type="string"/>
    <property column="ROLE" name="jobtitle" type="string"/>
    <property column="UNIT" name="unit" type="string"/>
    <property column="TECHNOLOGY" name="technology" type="string"/>

Run the application. Sample screen shots are shown below.

Output can be verified in the database as below.


Integrating Struts 2.0 with Hibernate is very simple. From the sample explained in the article, you can see that there is no need of using any separate pluggins for this. What is required is to get the SessionFactory object in the Action class and use it the way you use it in normal Java Applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!