首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 與 Struts 整合實戰:ActionSupport 方案深度解析

     編輯:Java 相關知識

Struts 1.x 作為經典 MVC 框架廣泛應用,Spring 輕量級容器提供強大的 DI/AOP 能力。本文通過實例詳解如何利用 Spring 的 ActionSupport 類整合 Struts,實現業務層解耦。

架構背景:為什麼整合而非遷移?

  • Struts 成熟穩定,團隊經驗豐富,遷移成本高
  • Spring DI 管理 Service/DAO 層,AOP 處理事務/日誌
  • Struts Action 僅作為 Web 層入口,委託給 Spring 管理的業務組件

整合核心步驟

1. 載入 Spring 上下文:ContextLoaderPlugIn

在 struts-config.xml 中聲明插件:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
    <set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>

啟動時自動載入 Spring 配置,構建 WebApplicationContext。

2. Action 繼承 ActionSupport 而非 Struts Action

public class SearchSubmit extends ActionSupport { // (1) 關鍵繼承
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        
        DynaActionForm searchForm = (DynaActionForm) form;
        String cardno = (String) searchForm.get("cardno");
        
        // (2) 獲取 Spring 容器
        ApplicationContext ctx = getWebApplicationContext();
        // (3) 從容器獲取業務 Bean
        CreditcardService service = (CreditcardService) ctx.getBean("creditcardService");
        
        CreditCard card = service.read(cardno.trim());
        if (card == null) {
            ActionErrors errors = new ActionErrors();
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("message.notfound"));
            saveErrors(request, errors);
            return mapping.findForward("failure");
        }
        request.setAttribute("creditcard", card);
        return mapping.findForward("success");
    }
}

方案優劣深度剖析

維度評價說明
開發效率⭐⭐⭐⭐⭐最簡單,無額外配置,Action 直接獲取 Bean
耦合度⭐⭐Action 硬依賴 Spring API,難以單元測試,替換容器需改代碼
AOP 支持❌Action 不在 Spring 管理下,無法套用事務/日誌切面
生命周期⚠️Action 由 Struts 實例化(單例/多例),非 Spring 管控

進階方案對比

  1. ActionSupport 方案(本文):最簡單,強耦合 Spring,無 AOP
  2. 委託代理模式:Action 精簡為委託者,真正業務邏輯在 Spring Bean 中,Action 通過 getWebApplicationContext() 獲取代理
  3. RequestProcessor 代理:自定義 RequestProcessor 讓 Spring 管理 Action 實例,實現完整 DI/AOP
  4. Spring MVC 遷移:長期最佳,但需重寫 Web 層

beans.xml 關鍵配置

<bean id="creditcardService" class="com.infotek.Creditcard.business.CreditcardServiceImpl">
    <property name="dao" ref="creditcardDao"/>
</bean>

<bean id="creditcardDao" class="com.infotek.Creditcard.dao.CreditcardDaoImpl">
    <property name="dataSource" ref="dataSource"/>
</bean>

總結與建議

ActionSupport 方案是「以最小代價引入 Spring DI」的戰術選擇,適合存量項目快速受益。但長期看,Action 應退化為薄薄的 Web 適配層,核心業務邏輯下沉至 Spring 管理的 Service 層,並逐步向 Spring MVC 或現代框架演進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved