SSH Framework Integration Idea
The three frameworks are applied to the Java EE Three-layer structure, and each layer uses a different framework. The idea of an SSH framework integration can be represented by the following figure:
Integration of the SSH Framework 1:0 barrier consolidation (with Hibernate configuration file)
We first integrate the STRUTS2 and spring frameworks, and then integrate the two frameworks of spring and hibernate. Consolidating Struts2 and spring frameworks
The thing to do with integrating STRUTS2 and spring is to give the creation of Struts2 's action to spring to configure.
The first step is to create a Web project that imports the STRUTS2 framework-related jar packages.
For the basic development of Struts2, you can refer to some sample code under apps in Struts-2.3.24, where Struts2-blank.war is a Struts2 empty project. We just need to unpack the Struts2-blank.war and then go to the Lib under Web-inf to view it.
In addition, the following jar packages are also required for STRUTS2: The development package for STRUTS2-CONVENTION-PLUGIN-2.3.24.JAR:STRUTS2 annotations STRUTS2-JSON-PLUGIN-2.3.24.JAR:STRUTS2 integrates Ajax to return JSON data struts2-spring-plugin-2.3.24.jar:struts2 integrate spring's plug-in package. In this article, I have only imported this jar package.
The second step is to write an action.
Create a cn.itcast.action package under the SRC directory and create a useraction under the package.
public class Useraction extends Actionsupport {
@Override public
String execute () throws Exception {
SYSTEM.OUT.PRINTLN ("Action ... ...");
return NONE;
}
}
The third step is to create the core configuration file for the Struts2, which is located under the SRC directory, and the name is Struts.xml. and configure useraction in this core profile.
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
"-//apache Software foundation//dtd struts Configuration 2.3//en"
"http:// Struts.apache.org/dtds/struts-2.3.dtd ">
<struts>
<package name=" Demo "extends=" Struts-default "namespace="/">
<action name=" user "class=" cn.itcast.action.UserAction "></action >
</package>
</struts>
At this point the Useraction class is created by Struts2 itself.
Note: When STRUTS2 and spring frameworks are consolidated, the STRUTS2 core configuration file has a fixed name and location, that is, the name can only be struts.xml and must be under the SRC directory.
The fourth step is to configure the STRUTS2 filter. That is, add the following configuration to the Web.xml configuration file:
<!--configuration Struts2 filter-->
<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>
Step fifth, import the spring framework-related jar packages. The Spring Framework Basic Development JAR Package:
AOP development-related jar packs:
Jar packages related to JDBC development:
Development related to Transaction management Jar Pack:
To consolidate hibernate jar packages:
Jar packages for whole and Web projects:
Step sixth, create the core configuration file--bean1.xml for spring.
Introducing constraints
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns=
"Http://www.springframework.org/schema/beans"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "http://www.springframework.org/ Schema/context "
xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "
xmlns:tx=" http:// Www.springframework.org/schema/tx "
xsi:schemalocation=" Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/ SCHEMA/AOP
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/ Schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
</beans>
Configure the spring listener, which adds the following configuration to the Web.xml configuration file:
<listener>
<listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>
</listener>
Specify the location of the spring configuration file, that is, add the following configuration to the Web.xml configuration file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> Classpath:bean1.xml</param-value> <!--because the Bean1.xml configuration file is in the SRC directory, it can be written directly-->
</context-param>
Step seventh, give useraction to spring to configure, which is to add the following configuration in the spring configuration file:
<!--Configure Action object-->
<bean id= "useraction" class= "Cn.itcast.action.UserAction" scope= "prototype" > </bean>
At this point, the Useraction object is configured in the spring configuration file--bean1.xml, and the Useraction object is also configured in the Struts2 profile--struts.xml. Obviously, this approach is undesirable. The solution is to configure the Useraction object only in the spring configuration file, not in the Struts2 configuration file. Therefore, the STRUTS2 configuration file should read:
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE struts public
"-//apache Software foundation//dtd struts Configuration 2.3//en"
"http:// Struts.apache.org/dtds/struts-2.3.dtd ">
<struts>
<package name=" Demo "extends=" Struts-default "namespace="/">
<!--do not write the action full path in the Action tab, the class attribute value is written in the ID value of the bean label of the spring Configuration Action Object- >
<action name= "user" class= "useraction" ></action>
</package>
</struts>
Here, the STRUTS2 and spring frameworks have been consolidated, and it's time to test if it's really what we want.
Create a Cn.itcast.dao package under the SRC directory and write a class--userdao.java for the DAO layer under the package.
public class Userdao {public
void Add () {
System.out.println ("dao .... ...");
}
Then create a cn.itcast.service package under the SRC directory and write a class--userservice.java of the service layer under the package, and invoke the method inside the class in the Userdao class.
public class UserService {
private Userdao Userdao;
public void Setuserdao (Userdao userdao) {
This.userdao = Userdao;
}
The public void Add () {
System.out.println ("service ... ...") is;
Userdao.add ();
}
Then, within the Useraction class, you call the method inside the UserService class.
public class Useraction extends Actionsupport {
private userservice userservice;
public void Setuserservice (UserService userservice) {
this.userservice = userservice;
}
@Override public
String execute () throws Exception {
System.out.println ("Action ...");
Userservice.add ();
return NONE;
}
}
Accordingly, spring's core configuration file will be modified to:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "&
Gt <!--Configure Action object--> <bean id= "useraction" class= "Cn.itcast.action.UserAction" scope= "prototype" > & Lt;property name= "UserService" ref= "UserService" ></PRoperty> </bean> <bean id= "UserService" class= "Cn.itcast.service.UserService" > <property Name= "Userdao" ref= "Userdao" ></property> </bean> <bean id= "Userdao" class= "Cn.itcast.dao.UserDa" O "></bean> </beans>
Finally, you can see the following output from the Eclipse console by entering address http://localhost:8080/Spring_day04_demo1/user.action in the browser address bar:
Action .....
Service ........
DAO ........ Integrating the spring and hibernate frameworks
As I've said before, to integrate the spring and hibernate frameworks, there are two things that need to be done to manage the configuration of the database information in the Hibernate core profile to spring. The creation of the sessionfactory inside the hibernate is given to spring to manage.
Let me elaborate on the concrete implementation of the Spring Framework integration hibernate framework.
The first step is to import hibernate development-related jar packs.
First import all the jar packages under the lib/required directory, because in this directory, contains the jar packages that are required to run the Hibernate project.
Then import the driver jar package for the MySQL database:
Then import the log-related jar package:
Where log4j packages are imported by spring.
In this step, you may experience the following two issues: Jar Pack conflict when importing Struts2 and hibernate jar packages (two jar packs have the same functionality, but not the same version), that is, there is a jar package in Struts2:
There is also a jar package inside the hibernate:
The solution is simply to remove the lower version of the jar package. When spring consolidates the persistence layer framework, you must also import the following jar packages:
The second step is to build the hibernate development environment.
Create an entity class. Create a cn.itcast.entity package under the SRC directory and write a user entity class under the package.
public class User {
private Integer uid;
Private String username;
Private String address;
Public Integer Getuid () {return
uid;
}
public void SetUid (Integer uid) {
this.uid = uid;
}
Public String GetUserName () {return
username;
}
public void Setusername (String username) {
this.username = username;
}
Public String getaddress () {return address
;
}
public void setaddress (String address) {
this.address = address;
}
}
Configure the Entity class mapping relationship, that is, to create the User.hbm.xml mapping file in the Cn.itcast.entity package:
<?xml version= "1.0"?>
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en"
"http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
<!--generated 2017-4-5 14:44:57 by hibernate Tools 3.4.0.cr1-->
< hibernate-mapping>
<class name= "Cn.itcast.entity.User" table= "T_user" >
<id name= "UID" type= " Java.lang.Integer ">
<column name=" uid "/>
<generator class=" native "/>
</id>
<property name= "username" type= "java.lang.String" >
<column name= "username"/>
</property >
<property name= "Address" type= "java.lang.String" >
<column name= "Address"/>
property>
</class>
Create the Hibernate core configuration file, which is to introduce the Hibernate.cfg.xml file in the SRC directory.
<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibernate.or G/dtd/hibernate-configuration-3.0.dtd ">
Note: If you simply use the Hibernate framework, the core profile name must be hibernate.cfg.xml and the location must be in the SRC directory. But when hibernate and the spring Framework are consolidated, the hibernate core configuration file has no fixed requirements for its name and location.
The third step is to give the information about the database configuration in the Hibernate core configuration file to spring for configuration. That is, the configuration of the database information in the Hibernate core profile is removed and is configured in spring's core configuration file:
<!--Configure connection pooling-->
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" >
< Property Name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property>
<property name= "Jdbcurl" Value= "Jdbc:mysql:///spring_lee" ></property>
<property name= "user" value= "root" ></property >
<property name= "password" value= "Yezi" ></property>
</bean>
In the fourth step, the creation of the sessionfactory inside the hibernate is given to spring to configure. The specific idea is: When the server starts, load the spring configuration file, and then create the objects in the configuration file. The creation of the Sessionfactory object can also be configured in the spring configuration file. And because the code to create the Sessionfactory object is not simply new, it's a multiline code, and the core code is as follows:
Load core configuration file
config = new Configuration (). Configure ();
Create Sessionfactory object
sessionfactory = Config.buildsessionfactory ();
So it's not possible to simply configure the spring configuration file with a <bean> tag. The spring framework, for the above scenario, encapsulates a class that configures objects of this class to create Sessionfactory objects. So we should add the following in the spring configuration file:
<!--configuration Sessionfactory create-->
<bean id= "sessionfactory" class= " Org.springframework.orm.hibernate5.LocalSessionFactoryBean ">
<!--1. Specify database location-->
<property Name= "DataSource" ref= "DataSource" ></property>
<!--2. Specify the hibernate core profile location to use-->
< Property Name= "Configlocations" value= "Classpath:hibernate.cfg.xml" ></property>
</bean>
Step fifth, I told you before. Spring provides different technologies for each layer in the Java EE three-tier architecture, and in the DAO layer, Spring provides the technology for JDBC templates that can be used to crud the database. Spring provides templates for many of the persistence layer technologies that simplify programming, as shown in the following illustration:
Now we're going to use the Hibernatetemplate template class inside the DAO layer, and as for what it is, I'll do a brief introduction later. The concrete action is: Inject the Hibernatetemplate template class object into the Userdao, and call the Save method inside the Hibernatetemplate template class to add a record to the database table. So the code for the Userdao class should be modified to:
public class Userdao {
//Hibernatetemplate template object is injected into DAO inside
private hibernatetemplate hibernatetemplate;
public void Sethibernatetemplate (Hibernatetemplate hibernatetemplate) {
this.hibernatetemplate = hibernatetemplate;
}
public void Add () {
//Add record to table////
/hibernatetemplate hibernatetemplate = new Hibernatetemplate Hibernatetemplate (sessionfactory);
Hibernatetemplate.save (entity);
SYSTEM.OUT.PRINTLN ("Dao ... ...... ...");
User user = new user ();
User.setusername ("Li Ahi");
User.setaddress ("Hubei Tianmen");
Hibernatetemplate.save (user);
}
Of course, changes to the spring configuration file are essential. So you should add the following configuration to the spring configuration file:
<bean id= "Userdao" class= "Cn.itcast.dao.UserDao" > <property name= "hibernatetemplate"
Hibernatetemplate "></property>
</bean>
<!--creating Hibernatetemplate template objects-->
< Bean id= "hibernatetemplate" class= "Org.springframework.orm.hibernate5.HibernateTemplate" >
<!-- Inject sessionfactory--> <property name= "sessionfactory" ref= "sessionfactory"
></property>
< /bean>
Step sixth, configure the spring transaction management.
Configuring the transaction manager
<!--1. Configure the transaction manager-->
<bean id= "TransactionManager" class= " Org.springframework.orm.hibernate5.HibernateTransactionManager ">
<property name=" sessionfactory "ref=" Sessionfactory "></property>
</bean>
The opening of annotation transaction management
<!--2. Turn on transaction annotations-->
<tx:annotation-driven transaction-manager= "TransactionManager" ></TX: Annotation-driven>
Add a @transactional annotation at the business level
@Transactional public
class UserService {
private Userdao Userdao;
public void Setuserdao (Userdao userdao) {
This.userdao = Userdao;
}
The public void Add () {
System.out.println ("service ... ...") is;
Userdao.add ();
}
When you start the Tomcat server, you will find a T_user table in the database, which is a well-deserved one. Then in the browser address bar to enter the address http://localhost:8080/Spring_day04_demo1/user.action to access, you can see the T_user table more than a record, as follows:
So far, the three hibernate-5.0.7+struts-2.3.24+spring-4.2.4 framework has been integrated. Hibernatetemplate Introduction
Hibernatetemplate The hibernate framework is encapsulated, directly call the Hibernatetemplate inside the method can be implemented to the database crud operation.
Hibernatetemplate common methods are as follows: Serializable save (object entity): Add operation void Update (object entity): Modify operation void Delete (object Entity): delete operation <T> t get (class<t> Entityclass, Serializable ID): Query <T> t load based on ID (class<t> Entityclass, Serializable ID): Query List Find (String querystring, Object ... values) based on ID: Query action methods The SSH framework consolidation process summarizes importing the associated jar packages.
A total of 42 jar packs. Build a STRUTS2 development environment
Create the action, introduce the Struts.xml configuration file, and configure an Action configuration Struts2 framework filter to build the Hibernate development environment
Create a mapping relationship between an entity class configuration entity class and a database table create a hibernate core configuration file, primarily by introducing a mapping profile to build a spring development environment
Create the spring core profile so that the spring configuration file is loaded at server startup
Configure the listener to specify the location of the spring configuration file Struts2 and the Spring framework consolidation
Leave the creation of the Struts2 action to spring to configure (remember that the action is an object of multiple instances). The ID value of the bean is written in the class attribute of the action tag in the Struts.xml configuration file. Integration of spring and hibernate frameworks
Manage the configuration of the database information in the Hibernate core configuration file to spring. The creation of the sessionfactory inside the hibernate is given to spring to manage. Use the Hibernatetemplate template class inside DAO
Inject the Hibernatetemplate template class object into the DAO inside the Hibernatetemplate template object inject the Sessionfactory configuration spring's transaction management SSH Framework Integration mode two: without hibernate configuration file
When spring consolidates the hibernate framework, you do not have to write the hibernate core configuration files. Let me give you an example to illustrate.
First copy the above SSH project, and then modify it on the basis of it.
Then look at the Hibernate core configuration file that was written before, and know that the Hibernate core configuration file contains the following: the necessary parameters to connect to the database hibernate the introduction of the configuration mapping file of the property connection pool
When spring consolidates the hibernate framework, you can configure the introduction of the basic information configuration and mapping files in the Hibernate core profile into the spring configuration file, although it is not possible to write the hibernate core configuration files. So the contents of the spring configuration file should be modified to:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "&
Gt <!--Configure connection pooling--> <bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" > <proper Ty name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property> <property name= "Jdbcurl" value= "Jdbc:mysql:///spring_lee" ></property> <proper
Ty name= "user" value= "root" ></property> <property name= "password" value= "Yezi" ></property>
</bean> <bean id= "sessionfactory" class= "Org.springframework.orm.hibernate5.LocalSessionFactoryBean" > <property name= "DataSource" ref= "DataSource" ></property> <!--<property name= "Configloca" tions "value=" Classpath:hibernate.cfg.xml "></property>--> <!--If you don't write the hibernate core profile, you don't need to write the above line configuration. --> <!--1. Hibernate the configuration of the basic information (written here)--> <property name= "Hibernateproperties" > & lt;props> <prop key= "Hibernate.show_sql" >true</prop> <prop key= "Hibernat E.format_sql ">true</prop> <prop key=" Hibernate.dialect ">org.hibernate.dialect.mysqldialect&
Lt;/prop> <prop key= "Hibernate.hbm2ddl.auto" >update</prop> </props> </property> <!--2. Introduce the mapping file into--> <property name= "Mappingresources" > <list>
;value>cn/itcast/entity/user.hbm.xml</value> <!--<value>...</value>--> </list> </property> </bean> <bean id= "TransactionManager" class= "Org.springfra Mework.orm.hibernate5.HibernateTransactionManager "> <property name=" sessionfactory "ref=" "Sessionfactory" ;</property> </bean> <tx:annotation-driven transaction-manager= "TransactionManager"/> < Bean id= "useraction" class= "Cn.itcast.action.UserAction" scope= "prototype" > <property name= "UserService" ref = "UserService" ></property> </bean> <bean id= "UserService" class= "Cn.itcast.service.UserService" > <property Name= "Userdao" ref= "Userdao" ></property> </bean> <bean id= "Userdao" class= "Cn.itcast.dao.UserD"
AO "> <property name=" hibernatetemplate "ref=" Hibernatetemplate "></property> </bean> <bean id= "Hibernatetemplate" class= "org.springframework.orm.hibernate5.HibernateTemplate" > <property name = "Sessionfactory" ref= "sessionfactory" ></property> </bean> </beans>
So far, the three hibernate-5.0.7+struts-2.3.24+spring-4.2.4 framework has been integrated. Either way you choose.