Spring and Struts2 and Hibernate Integration(Struts + Spring + Hibernate)

In this blog we will learn how to integrate Spring with a Struts 2 and Hibernate project. This blog will guide you through step by step integration of spring in a struts and hibernate web application.

Project Structure
Here is a snapshot for overall project structure in eclipse IDE. Create a package structure as shown here   and add required files and libraries as per the later part of this blog.

spring-struts-integration

Libraries Used
Here is a snapshot of all libraries that are being used in this application. The libraries are taken from struts 2, hibernate and spring distribution packages. Before we start with struts-spring integration project
be sure that a correct set of libraries are added to lib folder.

spring-struts-integration

Database
Open mysql workbench and run following script to make a test database for our application. In this particular application we are taking a student_data table that would be mapped by an java object using hibernate mappings and configuration.
DROP TABLE IF EXISTS `student_data`; /*!40101 SET @saved_cs_client   = @@character_set_client */

; /*!40101 SET character_set_client = utf8 */; 
CREATE TABLE `student_data` 
  ( 
     `student_id`  INT(11) NOT NULL auto_increment, 
     `firstname`   VARCHAR(45) DEFAULT NULL, 
     `middlename`  VARCHAR(45) DEFAULT NULL, 
     `lastname`    VARCHAR(45) DEFAULT NULL, 
     `phonenumber` VARCHAR(45) DEFAULT NULL, 
     `gender`      VARCHAR(45) DEFAULT NULL, 
     `city`        VARCHAR(45) DEFAULT NULL, 
     `emailid`     VARCHAR(45) DEFAULT NULL, 
     PRIMARY KEY (`student_id`) 
  ) 
engine=innodb 
auto_increment=3 
DEFAULT charset=latin1; /*!40101 SET character_set_client = @saved_cs_client */; 

WebContent\WEB-INF\web.xml
web.xml is the starting point for every java web application ,it tells the container about project flow and request-response cycle. We have added a struts 2 filter with /* mapping, it tells the container that all upcoming requests are going to be served by struts 2 itself. Later on we have added  a context loader class and given the path of applicationContext.xml file. applicationContext.xml is the core of spring and it is used to configure all spring side of work flow.
<?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>Oodles_struts2SpringHibernate</display-name>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>WEB-INF/applicationContext.xml</param-value>
   </context-param>
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

WebContent\index.jsp
Our hello world application starts with a welcome file named index.jsp. Here we have added a struts-tags tag library that makes it easy to generate html response dynamically. This page shows up a hyperlink, in href attribute we have used a struts url tag it makes the link to call a action named formAction.
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
   <title>Java Guys | Struts 2+ Spring + Hibernate 3</title>
   <body style="{font-family:MS Sans Serif;text-align: center; }">
      <h3>Welcome to Struts 2 + Spring 3 + Hibernate Integration !</h3>
      </br>
      <h3>Hello World Example</h3>
      </br>Lets Start now !<a href="<s:url action="formAction"/>">Please Click Here</a>
   </body>
</html>

WebContent\Form.jsp
Struts 2 provides a effective tag libraries support that can be used to create a dynamic html content. This page shows a form with some input fields, on submit createBean action is called and form data is moved to createBean action.
<%@ taglib uri="/struts-tags" prefix="s" %>
<h3>Please Enter your details here !</br></h3>
</br></br>
<html>
   <title>Java Guys | Struts 2+ Spring + Hibernate 3</title>
   <body style="{font-family:MS Sans Serif;text-align: center; }">
      <center>
         <s:form method="post" action="createBean.action">
            <s:textfield label="First Name" name="firstName"/>
            <s:textfield label="Middle Name" name="middleName"/>
            <s:textfield label="Last Name" name="lastName"/>
            <s:textfield label="Phone Number" name="phoneNumber"/>
            <s:textfield label="Email Id" name="emailId"/>
            <s:radio list="{'Male','Female'}" label="Gender" name="gender"></s:radio>
            <s:select list="{'Gurgaon','Moradabad','Delhi','Noida'}" name="city" label="City"></s:select>
            <s:submit label="Save"></s:submit>
         </s:form>
      </center>
   </body>
</html>

src\struts.xml
In Struts 2 all action mappings and configuration goes into a xml file called struts.xml. Which action is going to serve the request and what jsp is to be rendered is decided in struts.xml using xml configurations.
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <package name="myPack" extends="struts-default">
      <action name="createBean" class="javaguys.tutorials.actions.CreateBean">
         <result >/Result.jsp</result>
      </action>
      <action name="formAction" class="javaguys.tutorials.actions.FormAction">
         <result >/Form.jsp</result>
      </action>
   </package>
</struts>

WebContent\WEB-INF\applicationContext.xml
Using spring we can eliminate the use of Hibernate configuration file hibernate.cfg.xml by adding database url and username-passsword in applicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
   <bean id="dataSourceBean" class="org.apache.commons.dbcp.BasicDataSource" >
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/javaguys_db"/>
      <property name="username" value="root"/>
      <property name="password" value="root"/>
   </bean>
   <bean id="sessionFactoryBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSourceBean"/>
      <property name="mappingResources">
         <list>
            <value>javaguys/tutorials/beans/Student.hbm.xml</value>
         </list>
      </property>
      <property name="hibernateProperties">
         <value>hibernate.dialect=org.hibernate.dialect.MySQLDialect    hibernate.hbm2ddl.auto=update    hibernate.show_sql=true    </value>
      </property>
   </bean>
   <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
      <property name="sessionFactory">
         <ref bean="sessionFactoryBean"/>
      </property>
   </bean>
   <bean id="studentDao" class="javaguys.tutorials.dao.StudentDao" >
      <property name="hibernateTemplate" ref="hibernateTemplate" />
   </bean>
   <bean id="createBean" class="javaguys.tutorials.actions.CreateBean" >
      <property name="studentDao" ref="studentDao" />
   </bean>
</beans>

src\javaguys\tutorials\actions\FormAction.java
package javaguys.tutorials.actions;

import com.opensymphony.xwork2.ActionSupport;

public class FormAction extends ActionSupport {
   public String execute() {
      return SUCCESS;
   }
}

src\javaguys\tutorials\actions\CreateBean.java
In struts 2 actions can be represented using a simple class so called pojo(plain old java object) , struts 2 provides some useful classes to be optionally extended in a action class so that some common features as form validation can be implemented easily. ActionSupport class is one of them that is being extended here, but remember that extending a helper class is totally optional in struts 2.
package javaguys.tutorials.actions;

import java.util.ArrayList;
import java.util.List;
import javaguys.tutorials.beans.Student;
import javaguys.tutorials.dao.StudentDao;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class CreateBean extends ActionSupport implements ModelDriven<Student> {
   private String studentId;
   private String firstName;
   private String middleName;
   private String lastName;
   private String phoneNumber;
   private String emailId;
   private String gender;
   private String city;
   private Student student = new Student();
   private StudentDao studentDao;
   ArrayList<Student> studentList = new ArrayList<Student>();

   @Overridepublic
   Student getModel() {
      return null;
   }

   public String execute() throws Exception {
      student.setCity(city);
      student.setEmailId(emailId);
      student.setFirstName(firstName);
      student.setGender(gender);
      student.setLastName(lastName);
      student.setMiddleName(middleName);
      student.setPhoneNumber(phoneNumber);
      studentDao.saveOrUpdate(student);
      studentList = (ArrayList<Student>) studentDao.getStudents();
      return SUCCESS;
   }

   public Student getStudent() {
      return student;
   }

   public void setStudent(Student student) {
      this.student = student;
   }

   public StudentDao getStudentDao() {
      return studentDao;
   }

   public void setStudentDao(StudentDao studentDao) {
      this.studentDao = studentDao;
   }

   public ArrayList<Student> getStudentList() {
      return studentList;
   }

   public void setStudentList(ArrayList<Student> studentList) {
      this.studentList = studentList;
   }

   public String getStudentId() {
      return studentId;
   }

   public void setStudentId(String studentId) {
      this.studentId = studentId;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getMiddleName() {
      return middleName;
   }

   public void setMiddleName(String middleName) {
      this.middleName = middleName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   public String getPhoneNumber() {
      return phoneNumber;
   }

   public void setPhoneNumber(String phoneNumber) {
      this.phoneNumber = phoneNumber;
   }

   public String getEmailId() {
      return emailId;
   }

   public void setEmailId(String emailId) {
      this.emailId = emailId;
   }

   public String getGender() {
      return gender;
   }

   public void setGender(String gender) {
      this.gender = gender;
   }

   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }
}

src\javaguys\tutorials\beans\Student.java
A plain java class is used as a bean to represents a unique identity in application. The objects of this class are going to be represented as a row and the fields of the class are going to represent attributes of a row in a table. Here in hibernate data is mapped from a java object to a relational database with hibernate mappings configuration.
package javaguys.tutorials.beans;

public class Student {
   private String studentId;
   private String firstName;
   private String middleName;
   private String lastName;
   private String phoneNumber;
   private String emailId;
   private String gender;
   private String city;

   public String getStudentId() {
      return studentId;
   }

   public void setStudentId(String studentId) {
      this.studentId = studentId;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getMiddleName() {
      return middleName;
   }

   public void setMiddleName(String middleName) {
      this.middleName = middleName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   public String getPhoneNumber() {
      return phoneNumber;
   }

   public void setPhoneNumber(String phoneNumber) {
      this.phoneNumber = phoneNumber;
   }

   public String getGender() {
      return gender;
   }

   public String getEmailId() {
      return emailId;
   }

   public void setEmailId(String emailId) {
      this.emailId = emailId;
   }

   public void setGender(String gender) {
      this.gender = gender;
   }

   public String getCity() {
      return city;
   }

   public void setCity(String city) {
      this.city = city;
   }
}

src\javaguys\tutorials\beans\Student.hbm.xml
In hbm.xml hbm stands for hibernate mappings ,this file maps java objects to relational databases. Every java object represents a row and a class represents a table in database.
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="javaguys.tutorials.beans.Student" table="student_data">
      <id name="studentId" column="student_id">
         <generator class="native"> </generator>
      </id>
      <property name="firstName" />
      <property name="middleName" />
      <property name="lastName" />
      <property name="phoneNumber" />
      <property name="emailId" />
      <property name="gender" />
      <property name="city" />
   </class>
</hibernate-mapping>
Now we are all done with our Spring Integration with Struts 2 and Hibernate Web Application , run application on Server to see the Result .

struts-spring-integration

struts-spring-integration

struts-spring-integration


Download "Spring + Struts + Hibernate integration Example project" from "SkyDrive"

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.