2012年3月23日金曜日

RequestMapping アノテーション


まず、ここまでの流れを整理すると
  1. Deplyment Descriptor(web.xml)に、ルートWebApplicationContextの立ち上げを行うブートストラップリスナー“ContextLoaderListener”を定義。
  2. 同じく web.xml で、DispatcherServlet の論理名(servlet-name 要素)と URL パターンの紐付けを行う(servlet-mapping 要素)。
  3. [servlet-name]-servlet.xml に、Controller や HandllerMapping, ViewResolver など、関連するビーンを定義。

サーブレットへのマッピング
Java Servlet Specification Version 3.0 によると、「サーブレットへのマッピングに使われるパスは、リクエスト URL からコンテキストパスとパスパラメーターを取り除いたもの」です。

サーブレットとのマッピングに使用される URL パターンは以下のように規定されています。
  • ‘/’で始まり‘/*’で終わる文字列:パスマッピング
  • プリフィックス‘*.’で始まる文字列:拡張子マッピング
  • 空文字列:コンテキストルートへのマッピングを行うスペシャルな URL パターン
  • ‘/’のみ:アプリケーションのデフォルトサーブレットへのマッピング
  • その他の文字列:完全一致

コントローラーへのマッピング
Spring Framework のリファレンス 16.2 The DispatcherServlet にあるイラスト Context hierarchy in Spring Web MVC を見るとなんとなくわかりますが、DispatcherServlet は、[servlet-name]-servlet.xml に基づいて生成された HandlerMapping インスタンスと連携して、リクエストを適切なコントローラーに割り振ります。

@RequestMapping アノテーション
受け取ったリクエストの終着点となるクラスやメソッドを指定するのが @RequestMapping アノテーションです。

package picboo.controller;
   :
  中 略
   :
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
   :
  中 略
   :

@Controller
public class AjaxAccountController {
   :
 @RequestMapping(value="/account/ajax/registration.html", method = RequestMethod.GET)
 public ModelAndView registration( ... ) {
   :
 }

 @RequestMapping(value="/account/ajax/confirmation.html", method = RequestMethod.POST)
 public ModelAndView confirmation( ... ) {
   :
 }

 @RequestMapping(value="/account/ajax/execution.html", method = RequestMethod.POST)
 public ModelAndView execution( ... ) {
   :
 }

}

この例では、registration, confirmation, execution の各メソッドに @RequestMapping アノテーションを付けています。「Controller と Handler Mapping」で、“/account/ajax/”というリクエストを AjaxAccountController に渡す設定を行いました。今度は、呼び出された AjaxAccountController 内のメソッドとリクエストの紐付けを @RequestMapping で行っています。

value および method は、いわゆる実行条件で、上記コードでは「/account/ajax/registration.html に対する GET リクエストが来たら registration メソッドを実行」、「/account/ajax/confirmation.html に対する POST メソッドが来たら confirmation メソッドを実行」という指定を行っています。

因みに、@RequestMapping アノテーションをクラス定義の部分(public class .. { .. } の前)に使えば、リクエストをクラスレベルでマッピングできます。

0 件のコメント:

コメントを投稿