what to learn first struts spring or hibernate
- Details
- Written by
- Concluding Updated on 03 August 2019 | Impress Email
Welcome to the first part of Struts - Bound - Hibernate integration tutorial series! Let imagine y'all are assigned a legacy project which is based-on Struts framework. Your critical mission is to add Jump and Hibernate to the projection and make sure these three guys (Struts, Bound and Hibernate) working together in harmony. And imagine this is the last chance you tin impress your boss (he promises y'all with salary increment or promotion if y'all can become the project done perfectly). Existence excited, you lot're looking effectually 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 y'all through the steps of developing a sample Java spider web project which utilizes the 3 frameworks Struts, Bound and Hide. The purpose of the application is to list all products from a MySQL database in a spider web page (JSP).
Before going into the details, permit's review some central points first. I think these key points are very important as it helps us understand what is actually going on with the integration at a high level.
Why Integration of Struts, Spring and Hibernate?
Struts is a web awarding framework, Spring is an enterprise application framework, and Hide is an ORM framework. Hibernate is working at the database layer, whereas both Struts and Spring tin can work at the web layer. Spring is more powerful than Struts and it can replace Struts. So if y'all are starting a new project with Spring and Hide, don't use Struts!
This kind of integration is but 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 practise.
How does the Integration of Struts, Leap and Hibernate piece of work?
In this kind of integration, Struts should intercept all requests coming to the application by working equally a dispatcher filter. Spring should act as a dependency injection container which also manages Hibernate session and provides transaction direction services.
The interesting betoken is that Struts' action classes are managed past Spring. Therefore, action mappings in Struts can refer to a Bound bean. This only can be washed past using the Spring Plug-in provided by Struts.
Back to the sample project we are going to develop in the next few minutes, I advise you employ the post-obit technologies:
- Java viii
- Struts Framework 2.3.20
- Spring Framework 4.1.iv.RELEASE
- Hide Framework 4.3.8.Final
- Tomcat 8.0
- Eclipse Luna (with Maven three)
- MySQL 5.5
- Apache Commons DBCP
Notation: in this kickoff function, all the configurations are done by using XML.
Now, let'south create a Dynamic Web projection in Eclipse then convert information technology to a Maven project (If yous don't know how to do this, follow the section 1 in the tutorial: Leap and Struts Integration Tutorial Function 1: XML Configuration). After the project is created, follow the steps below:
ane. Setting Upwards Database
Execute the following MySQL script to create a database called productsdb with a tabular array called product:
CREATE DATABASE `productsdb`; CREATE Table `production` ( `product_id` int(eleven) NOT Nil AUTO_INCREMENT, `name` varchar(128) NOT Zippo, `description` varchar(512) NOT NULL, `cost` float NOT Goose egg, Master Primal (`product_id`) )
Our application will list all products from the product tabular array. Remember to insert some dummy data for testing the application later.
two. Adding Maven Dependencies
First, declare properties for version numbers of Coffee, Struts, Bound, Hide and MySQL Connector library every bit follows:
<properties> <java-version>1.8</coffee-version> <org.springframework-version>iv.ane.4.RELEASE</org.springframework-version> <org.strutsframework-version>2.iii.20</org.strutsframework-version> <org.hibernateframework-version>4.3.viii.Concluding</org.hibernateframework-version> <org.mysqlconnector-version>5.i.34</org.mysqlconnector-version> </backdrop>
Dependencies for Spring framework:
<dependency> <groupId>org.springframework</groupId> <artifactId>jump-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-back up</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>bound-orm</artifactId> <version>${org.springframework-version}</version> <type>jar</type> <scope>compile</scope> </dependency>
Dependencies for Struts framework:
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${org.strutsframework-version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${org.strutsframework-version}</version> </dependency>
Dependencies for Hide ORM framework:
<dependency> <groupId>org.hibernate</groupId> <artifactId>hide-core</artifactId> <version>${org.hibernateframework-version}</version> </dependency>
Dependency for Apache Commons DBCP (database connexion pooling):
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.0</version> </dependency>
Dependency for MySQL Connector-Java library:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${org.mysqlconnector-version}</version> </dependency>
For the complete content of Maven configuration file, await for the pom.xml file in the attached project.
3. Coding and Mapping Model Course
Create a POJO class ( Production.java ) to model the product tabular array in the database:
/** * Copyright CodeJava.net To Present * All rights reserved. */ package net.codejava.framework.model; public course Product { private long id; private String name; individual String description; private float toll; public long getId() { render id; } public void setId(long id) { this.id = id; } public Cord getName() { return name; } public void setName(Cord name) { this.name = name; } public Cord getDescription() { return description; } public void setDescription(Cord description) { this.clarification = description; } public float getPrice() { return toll; } public void setPrice(float toll) { this.cost = price; } }
And here's its mapping class ( Production.hbm.xml ):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="internet.codejava.framework.model"> <class name="Product" tabular array="PRODUCT"> <id name="id" cavalcade="PRODUCT_ID"> <generator class="native"/> </id> <property proper name="name" /> <holding proper noun="description" /> <property name="price" /> </grade> </hibernate-mapping>
This is a pretty simple XML mapping file which tells Hibernate how to map the to a higher place POJO class with the table in the database.
4. Coding DAO Classes
Because our application has but office - list all products - hence the following DAO interface ( ProductDAO.java ):
/** * Copyright CodeJava.cyberspace To Present * All rights reserved. */ package net.codejava.framework.dao; import coffee.util.List; import cyberspace.codejava.framework.model.Product; public interface ProductDAO { List<Product> list(); }
And the post-obit code is for the implementation grade ( ProductDAOImpl.java ):
/** * Copyright CodeJava.internet To Present * All rights reserved. */ package net.codejava.framework.dao; import java.util.List; import javax.transaction.Transactional; import org.hibernate.Criteria; import org.hide.SessionFactory; import cyberspace.codejava.framework.model.Production; public form ProductDAOImpl implements ProductDAO { private SessionFactory sessionFactory; public ProductDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override @Transactional public List<Product> listing() { @SuppressWarnings("unchecked") List<Product> listProduct = (List<Product>) sessionFactory.getCurrentSession().createCriteria(Production.form) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) .list(); render listProduct; } }
Equally you can see, the list() method but returns a list of products from the database through the SessionFactory which is injected via constructor by Bound.
v. Coding Struts Activity Class
Now, create a class that acts every bit a Struts action ( ListProductAction.java ) with the following code:
/** * Copyright CodeJava.net To Present * All rights reserved. */ bundle 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 grade ListProductAction extends ActionSupport { private ProductDAO productDAO; private Listing<Production> listProduct; public void setProductDAO(ProductDAO productDAO) { this.productDAO = productDAO; } public String execute() { listProduct = productDAO.listing(); return SUCCESS; } public List<Product> getListProduct() { render 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 fourth dimension to brand configurations to wire the pieces of Struts, Spring and Hibernate together.
6. Coding View Page
Create a JSP file called ProductList.jsp under the /Spider web-INF/views directory (create the views directory first) with the post-obit code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-viii"%> <%@ taglib prefix="south" uri="/struts-tags" %> <!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>Product List</title> </head> <body> <div align="centre"> <table width="lxxx%" border="1" manner="border-collapse: collapse;"> <tr> <th>No</th> <th>Production Name</th> <th>Description</th> <thursday>Price</th> </tr> <s:iterator value="listProduct" status="stat"> <tr> <td><s:property value="#stat.count" /></td> <td><south:holding value="name" /></td> <td><s:holding value="description" /></td> <td><due south:holding value="price" /></td> </tr> </southward:iterator> </table> </div> </body> </html>
This page merely uses Struts tag to iterate over the drove of products and display result in an HTML tabular array.
7. Configuring Web Deployment Descriptor (web.xml)
Configure Struts and Spring in the web.xml file equally follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <brandish-name>Struts2Spring4Hibernate4XML</display-name> <context-param> <param-proper name>contextConfigLocation</param-name> <param-value>/Spider web-INF/jump/appContext.xml</param-value> </context-param> <listener> <listener-grade>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>DispatcherFilter</filter-proper noun> <filter-grade>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>DispatcherFilter</filter-proper name> <url-design>/*</url-pattern> </filter-mapping> </spider web-app>
Here, Struts is configured equally the dispatcher servlet in order to intercept all requests coming to the application, whereas Spring is configured every bit a context listener which is responsible for managing beans and injecting dependencies.
viii. Configuring Hibernate framework
Create an XML file called hibernate.cfg.xml nether the source directory with the following content:
<?xml version='ane.0' encoding='utf-eight'?> <!DOCTYPE hide-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-mill> <property name="dialect">org.hibernate.dialect.MySQLDialect</holding> <property name="show_sql">true</property> <mapping resource="net/codejava/framework/model/Product.hbm.xml"/> </session-factory> </hibernate-configuration>
In this Hibernate configuration file, we simply specify the database dialect is MySQL and tell Hibernate where to wait for the mapping file.
9. Configuring Struts framework
On the Struts side, create an XML file called struts.xml under the source folder and put the post-obit code:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration ii.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <parcel name="Struts2Spring4Hibernate4Demo" extends="struts-default"> <action name="listProduct" class="listProductActionBean"> <issue name="success">/Spider web-INF/views/ProductList.jsp</result> </action> </package> </struts>
Hither, we declare an action mapping to handle the URL /listProduct . Note that the action form is now pointing to proper noun of a edible 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/bound directory (create the spring directory first). Put the following XML code:
<?xml version="one.0" encoding="UTF-eight"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://world wide web.springframework.org/schema/beans/jump-beans.xsd http://www.springframework.org/schema/tx http://world wide web.springframework.org/schema/tx/spring-tx.xsd"> <bean id="listProductActionBean" class="net.codejava.framework.action.ListProductAction"> <holding name="productDAO" ref="productDAO" /> </bean> <edible bean id="productDAO" class="net.codejava.framework.dao.ProductDAOImpl"> <constructor-arg> <ref bean="sessionFactory" /> </constructor-arg> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property proper noun="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hide.cfg.xml" /> </bean> <edible bean id="dataSource" course="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property proper noun="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/productsdb" /> <property name="username" value="root" /> <property proper name="countersign" value="[e-mail protected]" /> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </edible bean> </beans>
From top to bottom, we declare the listProductActionBean which is the Struts action. So productDAO edible bean is declared and injected to the listProductActionBean .
The productDAO requires a SessionFactory and then we declare a SessionFactory bean adjacent. In plough, 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 direction services for the productDAO edible bean.
11. Final Project Structure
Hurray! We have washed all the heavy stuff of Java code and XML configuration. Looking back, we have the following project structure:
Refer to this in instance y'all did something wrong.
12. Testing the Struts Spring Hibernate Awarding
Now, information technology's time to enjoy our hard work done so far. Deploy the awarding on Tomcat server and type the post-obit URL into your browser to access the awarding:
http://localhost:8080/Struts2Spring4Hibernate4XML/listProduct
And here'due south our sweet result:
Read Role 2: Struts - Spring - Hide Integration Tutorial with Java-Based and Annotations
Other Struts Tutorials:
- Introduction to Struts framework
- Struts beginner tutorial (Eclipse + Tomcat + XML)
- Struts Beginner Tutorial with Annotations
- Struts beginner tutorial with Convention Plugin (nil-configuration)
- How to handle exceptions in Struts
- Struts Form Handling Tutorial
- Struts Form Validation Tutorial
- Send e-mail with attachments in Struts
- Struts File Download Tutorial
About the Author:
Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the time of Coffee 1.four and has been falling in beloved with Java since and then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
Source: https://mail.codejava.net/frameworks/struts/struts-2-spring-4-hibernate-4-integration-tutorial-part-1-xml-configuration
0 Response to "what to learn first struts spring or hibernate"
Post a Comment