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 Employee.java 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. Employee.java
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 Registration.java

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 – Registration.java
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();
            session.saveOrUpdate(employee);
            transaction .commit();
            System.out.println("Record Inserted Successfully");
        } catch (HibernateException hibernateException) {
            System.out.println(hibernateException.getMessage());
            session.close();
            return "ERROR";
        }
        return "SUCCESS";
    }

    @Override
    public Employee getModel() {
        return employee;
    }
    @Override
    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"
    "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags"  prefix="s"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <center>
            <!-- <img src="PDT_TVM_SMall.JPG"/> -->
            <h1>Registration Form</h1>
            <s:form action="Registration">
                <table bgcolor="pink">
                    <tr>
                        <td>
                            <s:textfield name="empno" label=" Employee Id " value="" />
                        </td>
                        <td>
                            <s:textfield name="name" label=" Name" />
                        </td>
                        <td>
                            <s:textfield name="jobtitle" label=" Job Title " />
                        </td>
                        <td>
                            <s:combobox label=" Business Unit " name="unit"
                                        headerValue="--- Please Select ---"
                                        headerKey="1"
                                        list="{'Retail','HR','Quality','R&D','Testing','Facilities'}" />
                        </td>
                        <td>
                            <s:combobox label=" Current Technology Area" name="technology"
                                        headerValue="--- Please Select ---"
                                        headerKey="1"
                                        list="{'Java','J2EE','.NET','Main Frame','Others'}"/>
                        </td>
                        <td colspan="0"><s:submit label="Register"/></td>
                    </tr>
                </table>
            </s:form>
        </center>
    </body>
</html>
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"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="s"  uri="/struts-tags"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body><center>
            <br>  <br>  <br>  <br>
            <h1 style="color:chocolate"> <s:property value="name"/> registered successfully !!</h1>
               </center>
           </body>
</html>
Listing 5 : Error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" errorPage="Error.jsp"%>
<!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>Error Page</title>
    </head>
    <body>
        <h1>Some Error Occurred !!  </h1>
    </body>
</html>

Oracle Database table structure

Listing 6 : web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.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>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Hibernate and Struts 2 configuration files

Listing 7 : Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!-- 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>
        </action>
    </package>
</struts>
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"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <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:@10.154.117.76:1521:oracle</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="Employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
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"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.myaction.Employee" table="StrutsHibEmployee">
    <id column="EMPNO" name="empno" type="int">
      <generator class="assigned"/>
    </id>
    <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"/>
  </class>
</hibernate-mapping>

Run the application. Sample screen shots are shown below.

Output can be verified in the database as below.

Summary

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.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. This is created by me and send to you.

Speak Your Mind

*