Last Updated on 03 August 2019   |   Print Email
Welcome to the first part of Struts - Spring - Hibernate integration tutorial series! Let imagine you are assigned a legacy project which is based-on Struts framework. Your critical mission is to add Spring and Hibernate to the project and make sure these three guys (Struts, Spring and Hibernate) working together in harmony. And imagine this is the last chance you can impress your boss (he promises you with salary increase or promotion if you can get the project done perfectly). Being excited, you’re looking around for solutions and finally reading this page!My friend, I want to tell you this: This tutorial is written for you to solve such problems. I will walk you through the steps of developing a sample Java web project which utilizes the three frameworks Struts, Spring and Hibernate. The purpose of the application is to list all products from a MySQL database in a web page (JSP).Before going into the details, let’s review some key points first. I think these key points are very important as it helps us understand what is really going on with the integration at a high level.
Why Integration of Struts, Spring and Hibernate?
Struts is a web application framework, Spring is an enterprise application framework, and Hibernate is an ORM framework. Hibernate is working at the database layer, whereas both Struts and Spring can work at the web layer. Spring is more powerful than Struts and it can replace Struts. So if you are starting a new project with Spring and Hibernate, don’t use Struts!This kind of integration is only necessary for legacy projects which were built with Struts and now you have to upgrade them with Spring and Hibernate while still keeping Struts. Therefore, there are very few Struts-Spring-Hibernate applications in practice.
How does the Integration of Struts, Spring and Hibernate work?
In this kind of integration, Struts should intercept all requests coming to the application by working as a dispatcher filter. Spring should act as a dependency injection container which also manages Hibernate session and provides transaction management services.The interesting point is that Struts’ action classes are managed by Spring. Therefore, action mappings in Struts can refer to a Spring bean. This only can be done by using the Spring Plug-in provided by Struts.
Back to the sample project we are going to develop in the next few minutes, I suggest you use the following technologies:
Java 8
Struts Framework 2.3.20
Spring Framework 4.1.4.RELEASE
Hibernate Framework 4.3.8.Final
Tomcat 8.0
Eclipse Luna (with Maven 3)
MySQL 5.5
Apache Commons DBCP
NOTE: in this first part, all the configurations are done by using XML.Now, let’s create a Dynamic Web project in Eclipse and then convert it to a Maven project (If you don’t know how to do this, follow the section 1 in the tutorial: Spring and Struts Integration Tutorial Part 1: XML Configuration). After the project is created, follow the steps below:
1. Setting Up Database
Execute the following MySQL script to create a database called productsdb with a table called product:
CREATE DATABASE `productsdb`;
CREATE TABLE `product` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`description` varchar(512) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`product_id`)
)
Our application will list all products from the product table. Remember to insert some dummy data for testing the application later.
2. Adding Maven Dependencies
First, declare properties for version numbers of Java, Struts, Spring, Hibernate and MySQL Connector library as follows:
This is a pretty simple XML mapping file which tells Hibernate how to map the above POJO class with the table in the database.
4. Coding DAO Classes
Because our application has only function - list all products - hence the following DAO interface (ProductDAO.java):
/**
* Copyright CodeJava.net To Present
* All rights reserved.
*/
package net.codejava.framework.dao;
import java.util.List;
import net.codejava.framework.model.Product;
public interface ProductDAO {
List<Product> list();
}
And the following code is for the implementation class (ProductDAOImpl.java):
/**
* Copyright CodeJava.net To Present
* All rights reserved.
*/
package net.codejava.framework.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import net.codejava.framework.model.Product;
public class ProductDAOImpl implements ProductDAO {
private SessionFactory sessionFactory;
public ProductDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
@Transactional
public List<Product> list() {
@SuppressWarnings("unchecked")
List<Product> listProduct = (List<Product>)
sessionFactory.getCurrentSession().createCriteria(Product.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
return listProduct;
}
}
As you can see, the list() method simply returns a list of products from the database through the SessionFactory which is injected via constructor by Spring.
5. Coding Struts Action Class
Now, create a class that acts as a Struts action (ListProductAction.java) with the following code:
/**
* Copyright CodeJava.net To Present
* All rights reserved.
*/
package net.codejava.framework.action;
import java.util.List;
import net.codejava.framework.dao.ProductDAO;
import net.codejava.framework.model.Product;
import com.opensymphony.xwork2.ActionSupport;
public class ListProductAction extends ActionSupport {
private ProductDAO productDAO;
private List<Product> listProduct;
public void setProductDAO(ProductDAO productDAO) {
this.productDAO = productDAO;
}
public String execute() {
listProduct = productDAO.list();
return SUCCESS;
}
public List<Product> getListProduct() {
return listProduct;
}
}
The action method execute() invokes the ProductDAO to retrieve a list of products which is used by the view (JSP) via the getter method getListProduct(). Spring will inject an instance of ProductDAO via setter method setProductDAO().So far we have done all the Java code parts. Now it’s time to make configurations to wire the pieces of Struts, Spring and Hibernate together.
6. Coding View Page
Create a JSP file called ProductList.jsp under the /WEB-INF/views directory (create the views directory first) with the following code:
Here, Struts is configured as the dispatcher servlet in order to intercept all requests coming to the application, whereas Spring is configured as a context listener which is responsible for managing beans and injecting dependencies.
8. Configuring Hibernate framework
Create an XML file called hibernate.cfg.xml under the source directory with the following content:
Here, we declare an action mapping to handle the URL /listProduct. Note that the action class is now pointing to name of a bean managed by Spring - listProductActionBean.We also configure mapping for the SUCCESS view that points to the ProductList.jsp page.
10. Configuring Spring framework
On the Spring side, create an XML file called appContext.xml under the /WEB-INF/spring directory (create the spring directory first). Put the following XML code:
From top to bottom, we declare the listProductActionBean which is the Struts action. Then productDAO bean is declared and injected to the listProductActionBean.The productDAO requires a SessionFactory so we declare a SessionFactory bean next. In turn, the SessionFactory requires a DataSource so next we declare a BasicDataSource bean which simply contains parameters for database connection.Finally we declare a TransactionManager on top of the SessionFactory in order to facilitate transaction management services for the productDAO bean.
11. Final Project Structure
Hurray! We have done all the heavy stuff of Java code and XML configuration. Looking back, we have the following project structure:Refer to this in case you did something wrong.
12. Testing the Struts Spring Hibernate Application
Now, it’s time to enjoy our hard work done so far. Deploy the application on Tomcat server and type the following URL into your browser to access the application:http://localhost:8080/Struts2Spring4Hibernate4XML/listProductAnd here’s our sweet result: Read Part 2: Struts - Spring - Hibernate Integration Tutorial with Java-Based and Annotations
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
WARN [org.jboss.as.server.deployment] (MSC service thread 1-5) JBAS015852: No se pudo poner un índice a la clase org/apache/commons/io/filefilter/AbstractFileFilter.class en /C:/jboss-eap-6.4/standalone/deployments/PruebaDeCodejava-0.0.1-SNAPSHOT.war/WEB-INF/lib/commons-io-2.2.jar: java.util.zip.ZipException: invalid LOC header (bad signature)
Comments
WARN [org.jboss.as.server.deployment] (MSC service thread 1-5) JBAS015852: No se pudo poner un índice a la clase org/apache/commons/io/filefilter/AbstractFileFilter.class en /C:/jboss-eap-6.4/standalone/deployments/PruebaDeCodejava-0.0.1-SNAPSHOT.war/WEB-INF/lib/commons-io-2.2.jar: java.util.zip.ZipException: invalid LOC header (bad signature)