Spring MVCの@RequestMappingアノテーションの例(Controller、メソッド、ヘッダー、パラメーター、@RequestParam、@PathVariableを含む)

@RequestMappingは、最も広く使用されているSpring MVCのアノテーションの一つです。org.springframework.web.bind.annotation.RequestMappingアノテーションは、ウェブリクエストを特定のハンドラクラスやハンドラメソッドにマッピングするために使用されます。 @RequestMappingは、コントローラクラスやメソッドに適用することができます。今日は、このアノテーションのさまざまな使用方法と、@PathVariable@RequestParamという他のアノテーションとの例を見ていきます。

Spring @RequestMapping

  1. @RequestMappingをクラスと一緒に使用:クラス定義と一緒に使用して、ベースのURIを作成することができます。例えば:

    @Controller
    @RequestMapping("/home")
    public class HomeController {
    
    }
    

    これにより、/homeがこのコントローラが使用されるURIになります。この概念は、ウェブアプリケーションのサーブレットコンテキストに非常に似ています。

  2. @RequestMappingをメソッドと共に使用すると、ハンドラーメソッドが使用されるURIパターンを指定できます。例えば:

    @RequestMapping(value="/method0")
    @ResponseBody
    public String method0(){
    	return "method0";
    }
    

    上記のアノテーションは、@RequestMapping("/method0")としても書くことができます。余談ですが、このWebリクエストのために文字列のレスポンスを送信するために@ResponseBodyを使用しています。これは、例をシンプルにするために行われます。いつものように、これらのメソッドをSpring MVCアプリケーションで使用し、単純なプログラムやスクリプトでテストします。

  3. @RequestMappingを使用した複数のURI:以下のように、複数のURIを処理するために単一のメソッドを使用することができます。

    @RequestMapping(value={"/method1","/method1/second"})
    @ResponseBody
    public String method1(){
    	return "method1";
    }
    

    RequestMappingアノテーションのソースコードを見ると、すべての変数が配列であることがわかります。ハンドラーメソッドのURIマッピングのために、String配列を作成することができます。

  4. @RequestMappingとHTTPメソッド:リクエストURIは同じでも、HTTPメソッドに基づいて異なる操作を実行したい場合があります。このメソッドが呼び出されるHTTPメソッドを絞り込むために、@RequestMappingメソッド変数を使用することができます。例えば:

    @RequestMapping(value="/method2", method=RequestMethod.POST)
    @ResponseBody
    public String method2(){
    	return "method2";
    }
    	
    @RequestMapping(value="/method3", method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String method3(){
    	return "method3";
    }
    
  5. @RequestMappingとヘッダー:ハンドラーメソッドを呼び出すために必要なヘッダーを指定することができます。例えば:

    @RequestMapping(value="/method4", headers="name=pankaj")
    @ResponseBody
    public String method4(){
    	return "method4";
    }
    	
    @RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})
    @ResponseBody
    public String method5(){
    	return "method5";
    }
    
  6. @RequestMappingとProduces、Consumes:リクエストの内容とレスポンスで使用するMIMEメッセージを判断するために、Content-TypeAcceptヘッダーを使用することができます。わかりやすさのために、@RequestMappingでは、リクエストのContent-TypeとレスポンスのContent-Typeを指定するためのproducesconsumes変数が提供されています。例えば:

    @RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html")
    @ResponseBody
    public String method6(){
    	return "method6";
    }
    

    上記のメソッドは、Content-Typeがtext/htmlのメッセージのみを受け取り、application/jsonapplication/xmlのタイプのメッセージを生成することができます。

Spring @PathVariable

  1. @RequestMapping@PathVariable:RequestMappingアノテーションは、URIの一部がパラメータとして機能する動的なURIを処理するために使用されます。正規表現を使用して、URIの動的パラメータが特定のタイプの入力のみを受け入れるように指定することもできます。これは、@PathVariableアノテーションと一緒に使用され、URI変数をメソッドの引数の1つにマップすることができます。例えば:

    @RequestMapping(value="/method7/{id}")
    @ResponseBody
    public String method7(@PathVariable("id") int id){
    	return "method7 with id="+id;
    }
    	
    @RequestMapping(value="/method8/{id:[\\d]+}/{name}")
    @ResponseBody
    public String method8(@PathVariable("id") long id, @PathVariable("name") String name){
    	return "method8 with id= "+id+" and name="+name;
    }
    

Spring @RequestParam

  1. @RequestMapping@RequestParamを使用してURLパラメータを取得する:時にはリクエストURLでパラメータを受け取ることがあります。主にGETリクエストで使用されます。@RequestMapping@RequestParamアノテーションを使用してURLパラメータを取得し、メソッドの引数にマッピングすることができます。例えば:
```
@RequestMapping(value="/method9")
@ResponseBody
public String method9(@RequestParam("id") int id){
	return "method9 with id= "+id;
}
```

For this method to work, the parameter name should be "id" and it should be of type int.
  1. @RequestMappingのデフォルトメソッド:メソッドのvalueが空の場合、それはコントローラークラスのデフォルトメソッドとして機能します。例えば:
```
@RequestMapping()
@ResponseBody
public String defaultMethod(){
	return "default method";
}
```

As you have seen above that we have mapped `/home` to `HomeController`, this method will be used for the default URI requests.
  1. @RequestMappingフォールバックメソッド:ハンドラーメソッドが一致しない場合でも、コントローラークラスにフォールバックメソッドを作成して、すべてのクライアントリクエストをキャッチすることができます。リクエストに対してハンドラーメソッドが存在しない場合、カスタムの404レスポンスページをユーザーに送信する際に便利です。
```
@RequestMapping("*")
@ResponseBody
public String fallbackMethod(){
	return "fallback method";
}
```

Spring RestMappingテストプログラム

上記の異なるメソッドをテストするために、Spring RestTemplateを使用することができますが、今日はデータのやり取りが少なくてシンプルなので、これらのメソッドをテストするためにcURLコマンドを使用します。以下にスクリプトspringTest.shを作成して、上記のメソッドを呼び出し、その出力を表示するようにしました。

#!/bin/bash

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method0";
curl https://localhost:9090/SpringRequestMappingExample/home/method0;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home";
curl https://localhost:9090/SpringRequestMappingExample/home;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/xyz";
curl https://localhost:9090/SpringRequestMappingExample/home/xyz;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1";
curl https://localhost:9090/SpringRequestMappingExample/home/method1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1/second";
curl https://localhost:9090/SpringRequestMappingExample/home/method1/second;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4";
curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5";
curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method6";
curl https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method7/1";
curl https://localhost:9090/SpringRequestMappingExample/home/method7/1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa";
curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20";
curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20;
printf "\n\n*****DONE*****\n\n";

注意:私はWebアプリケーションをTomcat-7にデプロイし、ポート9090で実行しています。SpringRequestMappingExampleはアプリケーションのサーブレットコンテキストです。コマンドラインでこのスクリプトを実行すると、以下の出力が得られます。

pankaj:~ pankaj$ ./springTest.sh 
curl https://localhost:9090/SpringRequestMappingExample/home/method0
method0

*****

curl https://localhost:9090/SpringRequestMappingExample/home
default method

*****

curl https://localhost:9090/SpringRequestMappingExample/home/xyz
fallback method

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method1
method1

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method1/second
method1

*****

curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2
method2

*****

curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3
method3

*****

curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3
method3

*****

curl -H name:pankaj https://localhost:9090/SpringRequestMappingExample/home/method4
method4

*****

curl -H name:pankaj -H id:1 https://localhost:9090/SpringRequestMappingExample/home/method5
method5

*****

curl -H Content-Type:text/html https://localhost:9090/SpringRequestMappingExample/home/method6
method6

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method6
fallback method

*****

curl -H Content-Type:text/html -H Accept:application/json -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT

method6

*****

curl -H Content-Type:text/html -H Accept:application/xml -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/xml
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT

method6

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method7/1
method7 with id=1

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa
method8 with id= 10 and name=Lisa

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20
method9 with id= 20

*****DONE*****

pankaj:~ pankaj$ 

これらのほとんどは自明ですが、デフォルトとフォールバックのメソッドを確認することをお勧めします。これでSpring RequestMappingの例は終わりです。この注釈とそのさまざまな機能を理解するのに役立つことを願っています。以下のリンクからサンプルプロジェクトをダウンロードし、さまざまなシナリオを試してさらに探索してみてください。

Spring MVC RequestMappingプロジェクトをダウンロードする

Source:
https://www.digitalocean.com/community/tutorials/spring-requestmapping-requestparam-pathvariable-example