spring + struts 無縫集成方式

spring + struts 集成 方法一

step1:依賴和基本常識
1. 首先要添加集成的核心jar包:struts2-spring-plugin-2.3.16.3.jar。
2. 按照名稱匹配的原則,定義業務Bean和Action中的setter方法,注意調用的是set方法而不是屬性,但是一般命名一致便於閱讀。
3. struts.xml中按照正常配置Action。

step2:web.xml文件配置

  • 1.指定spring文件存放的位置,如果存放在 /WEB/INF/目錄下,且文件名爲applicationContext.xml,該配置可以省略。
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
  • 2.該監聽器用於在web環境中啓動spring容器。
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 3.下面過濾器是爲了解決延遲加載後會話爲空的問題,它把一個Hibernate Session和一次完整的請求過程綁定,如圖1。需要注意的是spring中定義的SessionFactory Bean(會話工廠)的id配置— id=”sessionFactory”
<filter>
     <filter-name>OpenSessionInViewFilter</filter-name>
     <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
     <filter-name>OpenSessionInViewFilter</filter-name>
     <url-pattern>*.action</url-pattern>
</filter-mapping>

上面監聽器對事務開關影響如下圖(藍色和黃色線條分別爲加和不加的開閉位置)。
這裏寫圖片描述
- 4.當然struts2的過濾器也需要配置,這不是本文重點。故截圖示意。
這裏寫圖片描述

到這裏spring + struts 集成方式文件配置OK。


spring + struts 集成 方法二

但是spring默認在按name(默認)或按type注入的,靈活性不足。如:同一個業務Bean用在不同的業務處理過程中,對dao和其他參數的需求不一樣,dao和參數的注入就不一樣。這就需要在spring中就要聲明2個業務Bean,這樣無論byType還是byName都不適用。如下圖:
這裏寫圖片描述
那麼就需要把Action直接聲明在spring中,如下圖:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章