Struts Spring統合の例

Struts + Spring統合の例

Apache Struts 1.xで開発されたWebアプリケーションで、Spring Iocコンテナで宣言されたBeanにアクセスする方法を示すチュートリアルを次に示します。

このStruts1.x + Springの例をダウンロード–Struts-Spring-Hibernate-Example.zip

Springには、Spring Iocコンテナで宣言されたアクセスBean用の「Struts固有」ソリューションが付属しています。

  1. Struts構成ファイルにSpringの既製Strutsプラグインを登録します。

  2. Strutsアクションクラスを変更して、Struts ActionクラスのサブクラスであるSpringのActionSupportクラスを拡張します。

  3. ActionSupportは、Spring Iocコンテナで宣言されたBeanにアクセスするための便利なgetWebApplicationContext()メソッドを提供します。

1. Struts + Springの依存関係

Struts 1.xと統合するには、Springに「spring-web.jar」および「spring-struts.jar」ライブラリが必要です。 SpringのWebサイトまたはMavenからダウンロードできます。
pom.xml

        
    
        org.springframework
        spring
        2.5.6
    

        
        org.springframework
        spring-web
        2.5.6
    

    
        org.springframework
        spring-struts
        2.0.8
    

2. Strutsプラグインを登録する

Struts構成ファイル(struts-config.xml)で、Springの既製のStrutsプラグイン「ContextLoaderPlugIn」を登録します。

struts-config.xml


    
    
        
    

ContextLoaderPlugIn」は、StrutsとSpringの間のすべての統合作業を処理します。 SpringのBeanxmlファイルを「contextConfigLocation」プロパティにロードできます。

SpringBeans.xml



    
    

3. Spring's ActionSupport

Struts Actionクラスで、Springの「ActionSupport」クラスを拡張し、「getWebApplicationContext()」メソッドを介してSpringのBeanを取得します。

CustomerBean.xml

    
        
    

Strutsアクション

package com.example.customer.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.springframework.web.struts.ActionSupport;

import com.example.customer.bo.CustomerBo;
import com.example.customer.model.Customer;

public class ListCustomerAction extends ActionSupport{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
    HttpServletRequest request,HttpServletResponse response)
        throws Exception {

    CustomerBo customerBo =
        (CustomerBo) getWebApplicationContext().getBean("customerBo");

    ...
    return mapping.findForward("success");

  }
}

完了しました。