spring--Three Frame integration

Source: Internet
Author: User

Integration Principle

Integration steps:

1. Guide Package

2. Configure the spring container separately

Import constraint (Spring-config.xml)

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xmlns= "Http://www.springframework.org/schema/beans"       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-4.2.xsdhttp://www.springframework.org/schema/context/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/CONTEXT/SPRING-CONTEXT-4.2.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-4.2.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

Configure spring to launch with Project (Web. xml)

<!--allows the spring container to be created with the start of the project and destroyed with the closure of the project--><listener>    <listener-class> org.springframework.web.context.contextloaderlistener</listener-class></listener><!-- Specify the location to load the spring configuration file--><context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:spring-config.xml</param-value></context-param>
3, separate configuration struts2

Configuring Core Filters

<!--configuring Struts2 core Filters--><filter>    <filter-name>struts2</filter-name>    < filter-class>org.apache.struts2.dispatcher.filter.strutsprepareandexecutefilter</filter-class></ filter><filter-mapping>    <filter-name>struts2</filter-name>    <url-pattern>/* </url-pattern></filter-mapping>
4, STRUTS2 and spring integration

Configuration Constants (Struts.xml)

<!--give the Struts object to spring to create--><constant name= "Struts.objectfactory" value= "Spring" ></constant>

Configuration Spring is responsible for creating the action and assembling

Spring-config.xml

<!--action--><!--Note: The action object must be scoped to a number of cases. This conforms to the STRUTS2 architecture--><bean name= "Useraction" class= " Cn.x5456.web.action.UserAction "scope=" prototype ">    <property name=" UserService "ref=" UserService "> </property></bean>

Struts.xml

<package name= "CRM" namespace= "/" extends= "Struts-default" >    <!--Configure global exceptions---    < global-exception-mappings>        <exception-mapping exception= "java.lang.RuntimeException" result= "error" ></exception-mapping>    </global-exception-mappings>    <action name= "useraction_*" class= " Useraction "method=" {1} > <!--change the value of class to the name of the spring management Object--        <result name= "error" type= "redirect" >/ login.jsp</result>        <result name= "Success" type= "redirect" >/index.htm</result>        < Allowed-methods>login</allowed-methods>     </action></package>
5. Configure Hibernate separately

Import entity Class &orm metadata

Configuration file

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http://www.hibernate.org/ Dtd/hibernate-configuration-3.0.dtd ">6. Spring Integration Hibernate

Give the Sessionfactory object to the Spring container management (you can not hibernate.xml the configuration file at this time)

  <!--Configure Sessionfactory to Container--<bean name= "Sessionfactory" class= " Org.springframework.orm.hibernate5.LocalSessionFactoryBean "> <!--Configure hibernate basic information-<property Name= "Hibernateproperties" > <props> <!--required configuration--<prop key= "h Ibernate.connection.driver_class ">com.mysql.jdbc.Driver</prop> <prop key=" hibernate.connection . url ">jdbc:mysql:///xingedb</prop> <prop key=" Hibernate.connection.username ">root</prop > <prop key= "Hibernate.connection.password" >xxx</prop> <prop key= "Hiberna Te.dialect >org.hibernate.dialect.MySQLDialect</prop> <!--optional configuration-<pro                P key= "Hibernate.show_sql" >true</prop> <prop key= "Hibernate.format_sql" >true</prop> <prop key= "Hibernate.hbm2ddl.auto" >update</pRop> </props> </property> <!--introduce ORM metadata that specifies the package path where ORM metadata is located, and spring automatically reads all the configurations in the package--&gt        ; <property name= "mappingdirectorylocations" value= "Classpath:cn/x5456/domain" ></property> </bean >
7. Spring Integrated C3P0 Connection pool

Prepare Db.properties

#加一个 (any) prefix to prevent collisions with keywords jdbc.jdbcurl=jdbc:mysql:///xingedbjdbc.driverclass=com.mysql.jdbc.driverjdbc.user= Rootjdbc.password=xxx

Configuration file

<!--1. Set Read Db.properties file--><context:property-placeholder location= "Classpath:db.properties" ></ context:property-placeholder><!--2. Set Connection pool--><bean name= "DataSource" class= " Com.mchange.v2.c3p0.ComboPooledDataSource "> <property name=" driverclass "value=" ${jdbc.driverclass} ">  </property> <property name= "Jdbcurl" value= "${jdbc.jdbcurl}" ></property> <property name= "User" Value= "${jdbc.user}" ></property> <property name= "Password" value= "${jdbc.password}" ></property ></bean><!--Configure Sessionfactory to container--><bean name= "sessionfactory" class= " Org.springframework.orm.hibernate5.LocalSessionFactoryBean "> <!--3. Inject the connection pool sessionfactory--> <property Name= "DataSource" ref= "DataSource" ></property> <!--Configure Hibernate basic information--<property name= "Hibernatep Roperties "> <props> <!--required configuration, because of the use of connection pooling (configured in the connection pool), these 4 items are not available – <!--<prop Ke Y= "Hibernate.connection.driver_class ">com.mysql.jdbc.Driver</prop>--> <!--<prop key=" hibernate. Connection.url ">jdbc:mysql:///xingedb</prop>--> <!--<prop key=" Hibernate.connection.username ">root</prop>--> <!--<prop key=" Hibernate.connection.password ">710130520a</prop>-- > <prop key= "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop> <!--available Optional configuration-<prop key= "Hibernate.show_sql" >true</prop> <prop key= "hibernate.format_sq    L ">true</prop> <prop key=" Hibernate.hbm2ddl.auto ">update</prop> </props> </property> <!--introduce ORM metadata that specifies the package path where ORM metadata is located, and spring automatically reads all the configurations in the package--<property name= "Mappingdirectoryloca tions "value=" Classpath:cn/x5456/domain "></property></bean>
8, Spring integrated Hibernate environment Operation database

Query method:

public class Userdaoimpl extends Hibernatedaosupport implements Userdao {//via integrated Hibernatedaosupport, Get hibernatetemplate Public user Getuserbyusercode (String user_code) {//Method one: hql query User u = Super.gethib Ernatetemplate (). Execute (new hibernatecallback<user> () {@Override public User doinhibernate (S                Ession session) throws Hibernateexception {String hql = "from User where user_code=?";                Query query = session.createquery (HQL);                Query.setparameter (0, User_code);                User U = (user) query.uniqueresult ();            return u;        }        });        return u;    Method Two: Criteria query Detachedcriteria DC = Detachedcriteria.forclass (User.class);        Offline Object Dc.add (Restrictions.eq ("User_code", User_code));  list<user> list = (list<user>) super.gethibernatetemplate (). Findbycriteria (DC);         Returns only list if (List!=null&&list.size () >0) {   Return List.get (0);        }else {return null; }    }}

Need to provide Sessionfactory object

<bean name= "Userdao" class= "Cn.x5456.dao.impl.UserDaoImpl" >    <property name= "sessionfactory" ref= " Sessionfactory "></property></bean>

9. Hibernate version of AOP transaction

Core transaction manager (only this and JDBC version < inject connection pool > different)

<!--core transaction manager--><bean Name= "TransactionManager" class= " Org.springframework.orm.hibernate5.HibernateTransactionManager ">    <property name=" sessionfactory "ref=" Sessionfactory "></property></bean>

Method One: Configure notifications and weave in

<!--configuration notification--><tx:advice id= "Txadvice" transaction-manager= "TransactionManager" > <tx:attributes> <tx:method name= "save*" isolation= "Repeatable_read" propagation= "REQUIRED" read-only= "false"/> <tx:meth OD name= "persist*" isolation= "Repeatable_read" propagation= "REQUIRED" read-only= "false"/> <tx:method name= "u pdate* "isolation=" Repeatable_read "propagation=" REQUIRED "read-only=" false "/> <tx:method name=" modify* "ISO lation= "Repeatable_read" propagation= "REQUIRED" read-only= "false"/> <tx:method name= "delete*" isolation= "REP Eatable_read "propagation=" REQUIRED "read-only=" false "/> <tx:method name=" remove* "isolation=" Repeatable_rea D "propagation=" REQUIRED "read-only=" false "/> <tx:method name=" get* "isolation=" repeatable_read "propagation = "REQUIRED" read-only= "true"/> <tx:method name= "find*" isolation= "Repeatable_read" propagation= "REQUIRED" re    Ad-only= "true"/></tx:attributes></tx:advice><!--configuration notifies the target object, configures the Pointcut, and configures the slice--><aop:config> <aop:pointcut expression= "Execution (* cn.x5456.service.impl.*serviceimpl.* (..))" id= "txpc"/> <aop:advisor advice-ref= " Txadvice "pointcut-ref=" txpc "/></aop:config>

Method Two: Configure annotation transactions

<!--open annotation transaction--><tx:annotation-driven transaction-manager= "TransactionManager"/>
10, expand the scope of the session

To avoid no-session problems when using lazy loading. Need to expand the scope of the session

Configure Filter

<!--Extended Session Scope Note: Any filter must be called before the filter of struts (because if the Struts interceptor is not released, it will simply not be able to get to our filter)--><filter>    <filter-name>openSessionInView</filter-name>    <filter-class> org.springframework.orm.hibernate5.support.opensessioninviewfilter</filter-class></filter><!-- Configuring STRUTS2 Core Filters--><filter>    <filter-name>struts2</filter-name>    <filter-class> org.apache.struts2.dispatcher.filter.strutsprepareandexecutefilter</filter-class></filter>< filter-mapping>    <filter-name>openSessionInView</filter-name>    <url-pattern>/*</ Url-pattern></filter-mapping><filter-mapping>    <filter-name>struts2</filter-name >    <url-pattern>/*</url-pattern></filter-mapping>

spring--Three Frame integration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.