Spring MVC MultiActionControllerアノテーションの例
このチュートリアルでは、@RequestMappingを使用して、Spring MVCアノテーションベースのMultiActionControllerを開発する方法を示します。
XMLベースのMultiActionControllerでは、URLを特定のメソッド名にマップするようにメソッド名リゾルバー(InternalPathMethodNameResolver、PropertiesMethodNameResolver、またはParameterMethodNameResolver)を構成する必要があります。 ただし、アノテーションのサポートにより、作業がより簡単になりました。URLを特定のメソッドにマップするために使用されるメソッド名リゾルバーとして@RequestMappingアノテーションを使用できるようになりました。
Note
この注釈ベースの例は、最後のSpring MVCMultiActionController XML-based exampleから変換されています。 だから、違いを比較して見つけてください。
設定するには、メソッド名の上にマッピングURLを指定して@RequestMappingを定義します。
package com.example.common.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CustomerController{
@RequestMapping("/customer/add.htm")
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("CustomerAddView");
}
@RequestMapping("/customer/delete.htm")
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("CustomerDeleteView");
}
@RequestMapping("/customer/update.htm")
public ModelAndView update(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("CustomerUpdateView");
}
@RequestMapping("/customer/list.htm")
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("CustomerListView");
}
}
これで、URLは次のパターンでメソッド名にマップされます。
-
/customer/add.htm –> add() method
-
/customer/delete.htm –> delete() method
-
/customer/update.htm –> update() method
-
/customer/list.htm –> list() method
Note
Spring MVCでは、この@RequestMappingは常に最も柔軟で使いやすいマッピングメカニズムです。