LoginSignup
5
9

More than 5 years have passed since last update.

Struts2→SpringMVCへの移行( Controller編 )

Posted at

Struts2からSpringMVCへ移行する際の前提

一番簡単な手順としては、

  • Struts2にSpring-pluginを導入しておき
  • Struts2のConventionプラグインを使ってActionクラスを書き
  • Struts2のActionクラスから実行するロジックをSpring framworkの管理下においてから
  • Strut2のActionをSpringMVCのControllerに置き換えます

他にも置き換えるものとして、Validation、View、Interceptorがありますが、それらは一応Struts2から独立したモジュールにできますので、順次置き換えもできます。今回はController編。

Actionクラスの前提

Struts2のActionクラスは、Conventionプラグインを利用して、アノテーションで記載するのが前提 です。Conventionプラグインを導入していない場合は、まずConventionプラグインを適用してActionクラスにStruts2のアノテーションを記載してください。

Struts2公式:Convention Plugin : https://struts.apache.org/docs/convention-plugin.html
Qiita:アノテーションベースでStruts2のActionクラスを記述する(2016 Spring Ver.) http://qiita.com/alpha_pz/items/4a97df916102dad2e2bc

Convention適用後のActionクラス

以下のようにActionクラスの実装は、

  • Web層との入出力
  • 画面遷移
  • ロジックの呼び出し

だけに留めます。

DisplayListAction.java
// Struts2-Convention
@Namespace("/")        // (1)
@ParentPackage("struts-thymeleaf")
@Results({@Result(name=ActionSupport.SUCCESS,type="thymeleaf-spring",location="list")})        // (3)
// Spring framework
@Controller
@Scope("prototype")
public class DisplayListAction extends ActionSupport {

    @Action("list") // Struts2-Convention        // (2)
    public String execute() throws Exception {
        products = service.search(param);
        return SUCCESS;
    }

    @Autowired // Spring framework
    ProductService service;

    @Setter        // (4)
    private String param;

    @Getter @Setter // Lombok        // (5)
    List<SampleProduct> products;
}

ここまで絞りきれば、SpringMVCのControllerに置き換えることができます。

SpringMVCのControllerへ

DisplayListController.java
@Controller
@RequestMapping("/")        // (1)
public class DisplayListController {

    @GetMapping("list")        // (2)
    public ModelAndView index(@RequestParam String param, ModelAndView mnv) {        // (4)
        List<SampleProduct> products = service.search(param);

        mnv.addObject("products", products);        // (5)
        mnv.setViewName("/list");        // (3)

        return mnv;
    }
}

こうすると、1対1のマッピングが可能です。

# 設定内容 Struts2 Convention Spring MVC
1 パス @Namespace @RequestMappings
2 制御部のパス @Action @GetMapping,@PostMappingなど
3 表示View @Results,@Result ModelAndViewのview名 または View名を単独でreturn
4 受け取るパラメータ メンバ変数+ミューテタメソッド(※1) メソッドの引数
5 レスポンスする内容 メンバ変数+アクセサメソッド(※2) メソッドの戻り値

※1 : いわゆるprivateフィールドとsetメソッド
※2 : いわゆるprivateフィールドとgetメソッド

移行するために大事なことは、Controller-Serviceの関係をSpringMVCにならってAction-Serviceの関係に持っていくこと、Actionクラスのフィールドで扱っていたリクエスト・レスポンスするオブジェクトをControllerのメソッドに持っていくことです。

5
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9