spring與struts1整合方案(二)

來源:互聯網
上載者:User

         上一節介紹了struts單獨植入系統的一種使用方式,以及WebApplicationContext在Servlet容器中初始化的原理,一般的Web應用就可以輕鬆的使用了。

         但是,隨著Struts的廣泛應用,把Struts和Spring整合起來,是一個需要面對的問題。Spring本身也提供了Struts的相關類,主要使用的有org.springframework.web.struts.ActionSupport,我們只要把自己的Action繼承自ActionSupport,就是可以調用ActionSupport中getWebApplicationContext()的方法取出WebApplicationContext。

         但這樣一來在Action中,跟上一節、一樣,需要取得商務邏輯的地方都要getBean,代碼看上去不夠簡潔。所以Spring又提供了另一個方法:用spring來管理struts的action,使用org.springframework.web.struts.ContextLoaderPlugIn外掛程式,該外掛程式在struts啟動時載入,這樣對於我們的action,就可以像管理bean一樣來管理。

以下只展示改動的代碼,原代碼參考spring與hibernate的整合   spring與struts1整合方案(一)

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config>  <form-beans />  <global-exceptions />  <global-forwards />    <action-mappings>    <!-- 使用DelegatingActionProxy將strut的action全權委託給spring容器管理。    DelegatingActionProxy是Action的子類,它把調用請求轉交給真正的Action實現    -->  <action path="/person/list" type="org.springframework.web.struts.DelegatingActionProxy"   validate="false" parameter="method">   <!-- jsp部署在WEB-INF下,防止使用者直接存取jsp -->  <forward name="list" path="/WEB-INF/person/list.jsp"></forward>  </action>  </action-mappings>    <!-- 國際化 -->  <message-resources parameter="struts.ApplicationResources" />    <!-- 將struts的action託管給spring容器管理  根據contextConfigLocation的設定檔載入ActionServlet -->  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  <set-property property="contextConfigLocation"  value="/WEB-INF/action-servlet-person.xml"/>  </plug-in>  </struts-config>

action-servlet-person.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-lazy-init="true"><!--此處配置的class是真實Action類的路徑 不能使用id命名,id不能包含特殊字元  --><bean name="/person/list" class="com.ch.action.PersonAction"><property name="personService" ref="personService" /></bean></beans>

PersonAction

package com.ch.action;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction;import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;import org.springframework.web.context.ContextLoader;import com.ch.dao.IPersonService;import com.ch.entity.Person;/** * 通常在設計中往往會要求同一個Action來處理用戶端發出的不同請求, * 所以使用DispatchAction類很好的解決了這類問題,通過設定parameter來配置傳遞不同的要求方法  * @author ch * */public class PersonAction extends DispatchAction {private IPersonService personService;@Overrideprotected ActionForward unspecified(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {// TODO Auto-generated method stubreturn list(mapping, form, request, response);}@SuppressWarnings("unchecked")public ActionForward list(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {// TODO Auto-generated method stubList<?> list = (List<Person>)personService.findAllPersons();request.setAttribute("list", list);return mapping.findForward("list");}public void setPersonService(IPersonService personService) {this.personService = personService;}}

部署運行結果:


其他整合方式:

1、使用spring的org.springframework.web.struts.ActionSupport (或者DispatchActionSupport):

Spring 的ActionSupport 繼承至 org.apache.struts.action.Action。 ActionSupport的子類可以獲得
WebApplicationContext類型的全域變數。通過getWebApplicationContext()可以獲得這個變數,繼而擷取bean對象。

public class PersonAction extends org.springframework.web.struts.ActionSupport {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {// TODO Auto-generated method stubWebApplicationContext wc = getWebApplicationContext();IPersonService personService = (IPersonService)wc.getBean("personService");List<?> list = (List<Person>)personService.findAllPersons();request.setAttribute("list", list);return mapping.findForward("list");}}

2、採用DelegatingRequestProcessor將處理轉寄給Spring容器中的bean:

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config>  <form-beans />  <global-exceptions />  <global-forwards />    <action-mappings>    <!-- 使用DelegatingActionProxy將strut的action全權委託給spring容器管理。    DelegatingActionProxy是Action的子類,它把調用請求轉交給真正的Action實現    -->  <action path="/person/list"   validate="false" parameter="method">   <!-- jsp部署在WEB-INF下,防止使用者直接存取jsp -->  <forward name="list" path="/WEB-INF/person/list.jsp"></forward>  </action>  </action-mappings>    <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />    <!-- 國際化 -->  <message-resources parameter="struts.ApplicationResources" />    <!-- 將struts的action託管給spring容器管理  根據contextConfigLocation的設定檔載入ActionServlet -->  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  <set-property property="contextConfigLocation"  value="/WEB-INF/action-servlet-person.xml"/>  </plug-in>  </struts-config>

        配置controller processorClass為DelegatingRequestProcessor(繼承自RequestProcessor)後,就是告訴Struts用DelegatingRequestProcessor來代替原來的RequestProcessor,Struts會將攔截到的使用者請求轉寄給spring Context下的相應bean,根據bean的name屬性來匹配。而Struts的Action配置無需配置type屬性(即使配置了type屬性也無作用,除非在spring的設定檔中找不到對應的name屬性bean)。
3、可以將action- servlet-person.xml中的配置bean移植到applicationContext.xml中,通過ContextLoaderListener來載入這些bean。這樣配置的話可以將Struts設定檔中的下列代碼去掉:

<!-- 將struts的action託管給spring容器管理  根據contextConfigLocation的設定檔載入ActionServlet -->  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">  <set-property property="contextConfigLocation"  value="/WEB-INF/action-servlet-person.xml"/>  </plug-in>

實際上ContextLoaderListener和ContextLoaderPlugIn的功能是重疊的,他們都是進行Spring配置的初始化工作的。區別是ContextLoaderListener與ContextLoaderPlugIn載入的bean不在同一個WebApplicationContext中,這在使用OpenSessionInView Filter模式時應注意這一點(具體內容會在下次介紹)。

總結

  • Struts與Spring的整合方式有三種:使用Spring 的 ActionSupport使用Spring 的 DelegatingRequestProcessor 類全權委託
  • 第一種方式ActionSupport整合了Struts的Action,使得struts和spring耦合在一起,並且編碼量(每次都要getWebApplicationContext和getBean)比較多,代碼不夠簡潔;第二種方式和第三種方式類似,Action 的建立和對象的依賴注入全部由IOC容器來完成。第二種方式RequestProcessor類已經被代理 如果要再實現自己的實現方式(如:編碼處理)就比較麻煩;所以優先使用第三種方式。
  • Struts與Spring的整合的後兩種應用了Spring IOC來管理Struts的Action,顧名思義,兩者即是在代理某對象。熟釋Struts的必然知曉RequestProcessor和Action,Spring就在這兩處切入到頁面層的請求鏈中(通過擴充Struts中的RequestProcessor、Action類),以便將截獲的請求傳入到Spring管理的Action執行個體中,從而實現頁面層到服務層的有效銜接。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.