spring和struts的整合

2021-08-30 12:10:38 字數 1968 閱讀 7104

struts 2框架整合spring很簡單,下面是整合的步驟。

1.複製檔案。複製struts2-spring-plugin-x-x-x.jar和spring.jar到web-inf/lib目錄下。其中的x對應了spring的版本號。還需要複製commons-logging.jar檔案到web-inf/lib目錄下。

2.配置struts.objectfactory屬性值。在struts.properties中設定struts.objectfactory屬性值:

struts.objectfactory = spring

或者在xml檔案中進行常量配置:

...3.配置spring***。在web.xml檔案中增加如下內容:

org.springframework.web.context.contextloaderlistener

<?xml version="1.0" encoding="utf-8"?>

contextconfiglocation

5.修改struts配置檔案。struts 2框架整合spring框架,需要在struts配置檔案中有所改變,下面是乙個示例:

foo.ftl

bar.ftl

該配置檔案中定義了兩個action配置:foo是乙個標準的struts 2框架action配置,指定了action實現類為com.acme.foo;bar對應的class並不存在,那麼框架將在spring配置檔案中查詢id屬性為「bar」的定義,該配置檔案如下所示:

<?xml version="1.0" encoding="utf-8"?>

...整合原理

struts2與spring的整合要用到spring外掛程式包struts2-spring-plugin-x-x-x.jar,這個包是同struts2一起發布的。spring外掛程式是通過覆蓋(override)struts2的objectfactory來增強核心框架物件的建立。當建立乙個物件的時候,它會用struts2配置檔案中的class屬性去和spring配置檔案中的id屬性進行關聯,如果能找到,則由spring建立,否則由struts 2框架自身建立,然後由spring來裝配。spring外掛程式具體有如下幾個作用:

— 允許spring建立action、interceptror和result。

— 由struts建立的物件能夠被spring裝配。

— 如果沒有使用spring objectfactory,提供了2個***來自動裝配action。

struts2-spring-plugin-x-x-x.jar外掛程式中有乙個struts-plugin.xml檔案,該檔案內容如下所示:

其中設定了struts 2框架常量struts.objectfactory的值為spring,實際上,spring是org.apache.struts2.spring.strutsspringobjectfactory類的縮寫,預設情況下所有由struts 2框架建立的物件都是由objectfactory例項化的,objectfactory提供了與其他ioc容器如spring、pico等整合的方法。覆蓋這個objectfactory的類必須繼承objectfactory類或者它的任何子類,並且要帶有乙個不帶引數的構造方法。在這裡用org.apache.struts2.spring.strutsspring objectfactory代替了預設的objectfactory。

如果action不是使用spring objectfactory建立的話,外掛程式提供了兩個***來自動裝配action,預設情況下框架使用的自動裝配策略是name,也就是說框架會去spring中尋找與action屬性名字相同的bean,可選的裝配策略還有:type、auto、constructor,開發者可以通過常量struts.objectfactory.spring.autowire來進行設定。

struts 2框架整合spring後,處理使用者請求的action並不是struts框架建立的,而是由spring外掛程式建立的。建立例項時,不是利用配置action時指定的class屬性值,根據bean的配置id屬性,從spring容器中獲得相應的例項。

Spring和Struts如何關聯

1.servlet 2.3及以上版本可以使用 相應配置如下 contextconfiglocation org.springframework.web.context.contextloaderlistener contextloaderservlet org.springframework.web...

整合struts和spring時

連線點 struts2的action由spring產生 大致如下 首先加入各自所需的jar包,連線時要加入struts2 spring plugin x.x.x.jar 1.修改web.xml加入struts的filter struts2 org.apache.struts2.dispatcher....

Struts 2整合Spring 經典

struts 2整合spring struts 2框架為整合其他技術提供了良好的可擴充套件性,可以通過外掛程式的方式來實現同spring技術的整合。13.2.1 整合步驟 struts 2框架整合spring很簡單,下面是整合的步驟。1 複製檔案。複製struts2 spring plugin x ...