Struts2+Hibernate+Spring整合步驟

1.Spring 整合Hibernate整合什麼?
1.由IOC容器來管理Hibernate的SessionFactory
2.讓Hibernate使用上Spring的聲明式事務

2.整合步驟:
1.加入Hibernate 
1)jar包
2)添加Hibernate配置文件 hibernate.cfg.xml
a.數據源需配置在IOC容器中,不再hibernate.cfg.xml文件中配置
b.關聯的.hbm.xml文件也在IOC容器配置SessionFactory實例時進行配置
c.配置hibernate的基本屬性,比如方言,sql顯示以及格式化,生成數據表的策略,二級緩存
d.編寫持久化類對應的.hbm.xml文件
2.加入Spring 
1)jar包
2)加入Spring的配置文件 applicationContext.xml
a.配置數據源
b.導入配置文件 db.properties
c.配置Hibernate的SessionFactory實例(通過spring提供的LocalSessionFactoryBean進行配置)
a)通過dataSource配置數據源屬性
b)通過configLocation配置Hibernate配置文件的名稱及位置(也可通過hibernateProperties屬性把hibernate.cfg.xml文件中的全部配置移過來)
c)通過mappingLocations配置Hibernate映射文件的名稱及位置,可以使用通配符
d.配置spring的聲明式事務
a)通過HibernateTransactionManager配置事務管理器(一定記得要配sessionFactory)
b)通過<tx:advice/>配置事務屬性,需要事務管理器
c)通過<aop:config/>配置事務切點,並把切點與事務屬性關聯起來
3.整合

2.Spring 如何在web應用中使用?
1.需額外加入的jar包:
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
2.配置文件跟非web應用的一樣
3.如何創建IOC容器?
1)非web應用在main方法中直接創建
2)web應用應該在web應用被服務器加載時就創建IOC容器

a.在ServletContextListener的initialized(ServletContextEvent sce)的方法中創建IOC容器後,

可以將其放在ServletContext(即application域)的一個屬性中。

b.實際上,spring的配置文件的名稱與位置應該是可以配置的!所以應該配置到當前web應用的初始化參數比較合適
<context-param>
  <param-name>configLocation</param-name>
  <param-value>applicationContext.xml</param-value>
</context-param>
4.實際上第三步spring已經幫我們解決了,我們只需要在web.xml文件中加入以下配置即可,獲取IOC容器可以通過WebApplicationContextUtils對象的getWebApplicationContext(ServletContext sc))方法獲取
<listener>  
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>applicationContext.xml</param-value>
</context-param>

3.Spring 如何整合struts2?
整合目標:讓IOC容器來管理struts2的Action
整合步驟:
1.正常加入struts2(struts-2.3.28.1\apps\struts2-blank\WEB-INF\lib下jar包),再到web.xml文件中配置struts2的核心過濾器
2.在IOC容器中配置struts2的Action時,需要配置scope屬性,其值一定要是prototype
<bean id="personAction" class="cn.lfd.spring.struts2.action.PersonAction" scope="prototype"></bean>
3.配置struts2的配置文件:action的節點的class屬性要指向IOC容器中的bean的id
<package name="default" namespace="/" extends="struts-default">
<action name="personAction" class="personAction">
<result>/success.jsp</result>
</action>
</package>
4.加入struts2-spring-plugin-2.3.28.1.jar包
5.整合原理:加入struts2-spring-plugin-2.3.28.1.jar包後,struts2會先從IOC容器中獲取Action的實例
發佈了52 篇原創文章 · 獲贊 24 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章