Spring Request Mapping

9188 ワード

1.概要
この記事では、Spring MVCにおける主要な注釈、@Request Mapping-は、ウェブ要求とSpring Controller方法のマッピングとして一般的に用いられることについて議論します.
全体の文章では、簡単なcurlコマンドによって各マッピングをテストします.
2、リクエストMappingの基礎
簡単な例を始めましょう.簡単な方法でHTTP要求を一つの方法にマッピングします.
2.1@Request Mapping–by Path
@RequestMapping(value = "/ex/foos")
@ResponseBody
public String getFoosBySimplePath() {
    return "Get some Foos";
}
簡単なcurlコマンドでこのマッピングをテストして、実行します.
curl-ihttp://localhost:8080/spring-rest/ex/foos
2.2.@Request Mapping–the HTTP Method
デフォルトの場合、@Request Mappingマッピングの方法はGET-もちろん変更できます.例えば、POST要求にマッピングします.
@RequestMapping(value = "/ex/foos", method = RequestMethod.POST)
@ResponseBody
public String postFoos() {
    return "Post some Foos";
}
curlコマンドはPOST要求をテストします.
curl-i-X POSThttp://localhost:8080/spring-rest/ex/foos
3.Request Mapping and HTTP Headers 3.1.@Request Mapping with the headers atribute
要求ヘッダをさらに指定することにより、マッピングファンを低減する.
@RequestMapping(value = "/ex/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
    return "Get some Foos with Header";
}
@Request Mappingのheader属性は、複数のヘッドを指定できます.
@RequestMapping(value = "/ex/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
    return "Get some Foos with Header";
}
私たちはcurl header supportでこの操作をテストします.
curl-i-H「key:val」http://localhost:8080/spring-rest/ex/foos
なお、curl分離キーと値の文法には1つのセミコロンが使われており、HTTPルールと同じで、Springでは等号が使われています.
3.2.@Request Mapping Consmes and Prodces
マッピング生成されたメディアタイプからController方法までは特に注目すべきものであり、Acceptヘッダに基づいてマッピング要求を行うことができます.上記で紹介された@Request MappingのHeader属性:
@RequestMapping(value = "/ex/foos", method = GET, headers = "Accept=application/json")
@ResponseBody
public String getFoosAsJsonFromBrowser() {
    return "Get some Foos with Header Old";
}
Acceptヘッダを定義するこのようなマッチング方式は柔軟である.これは含まれていればいいので、同じではない.したがって、以下の要求のように正確なマッピングが可能である.
curl-H「Acctept:appication/json,text/html」http://localhost:8080/spring-rest/ex/foos
Spring 3.1から@Request Mappingの注釈はproducesとconsumesの属性があり、この目的を達成することができる.
@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
    return "Get some Foos with Header New";
}
Spring 3.1から、header属性のこのような古い方式で自動的に新しいproduces機構に変換されるので、結果は同じです.
これは同じ方法でガールを使用します.
curl-H「Accept:appication/json」http://localhost:8080/spring-rest/ex/foos
また、produces属性も複数の値をサポートしています.
@Request Mapping(value=「/ex/foos」、produces={appication/json}、「appication/xml」)
これらをしっかり覚えてください.acceptヘッダの新旧方式を指定します.同じマッピングに基づいていますので、Springはそれらの二つを同時に定義できません.二つの結果が出たら、次のようになります.
Caused by: java.lang.IllegalStateException: Ambiguous mapping found.
Cannot map 'fooController' bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromREST()
to {[/ex/foos],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}:
There is already 'fooController' bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromBrowser()
mapped.
producesとconsumesのメカニズムについての最後のポイントは、-ほとんどの他の注釈とは異なり、クラス上に定義されている場合、方法上の注釈は補充されず、クラス上の情報を書き換えることである.
4.Request Mapping with Path Varables
@PathVarableによってURIを注釈マッピングする部分は一つの変数を結びつけることができます.
4.1.Single@PathVarable
単一変数の簡単な例を使用します.
@RequestMapping(value = "/ex/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable("id") long id) {
   return "Get a specific Foo with id=" + id;
}
curlでテスト:
curlhttp://localhost:8080/spring-rest/ex/foos/1
方法のパラメータ名とパス内の変数名が一致する場合、値のない@PathVarableで簡略化できます.
@RequestMapping(value = "/ex/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable String id) {
   return "Get a specific Foo with id=" + id;
}
注意:@PathVarableは自動的にタイプ転換できるので、idをこう宣言することができます.
@PathVarable long id
4.2.Multiple@PathVarable
より複雑なURIは、URIの複数の部分を複数の値にマッピングする必要がある:
@RequestMapping(value = "/ex/foos/{fooid}/bar/{barid}")
@ResponseBody
public String getFoosBySimplePathWithPathVariables
  (@PathVariable long fooid, @PathVariable long barid) {
    return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid;
}
curlでテストすると以下のようになります.
curlhttp://localhost:8080/spring-rest/ex/foos/1/bar/2
4.3.@PathVarable with RegEx
@PathVarableをマッピングする場合、正規表現を使用することができます.例えば、マッピングがidの値に対して数値タイプのみを受信することを制限します.
@RequestMapping(value = "/ex/bars/{numericId:[\d]+}")
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
    return "Get a specific Bar with id=" + numericId;
}
これは以下のURIマッチングを意味する.
http://localhost:8080/spring-rest/ex/bars/1
これはだめです
http://localhost:8080/spring-rest/ex/bars/abc
5.Request Mapping with Request Parameeters
@Request Mappingは@Request Paramで注釈するとURLパラメータに容易にマッピングできます.
例えば、要求をURIにマッピングする.
http://localhost:8080/spring-rest/ex/bars?id=100
@RequestMapping(value = "/ex/bars")
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}
私たちはcontroller法で署名中の@Request Param(「id」)の注釈でパラメータIDの値を取得した.
パラメータID付きの要求を送信します.Curlでのパラメータサポートを使用します.
curl-i-d id=100http://localhost:8080/spring-rest/ex/bars
この例ではパラメータは宣言せずに直接結合される.
より高度なスキームの場合、@Request Mappingは、別の縮小要求マッピングにパラメータを正確に定義することができる.
@RequestMapping(value = "/ex/bars", params = "id")
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") long id) {
    return "Get a specific Bar with id=" + id;
}
より柔軟なマッピングも許容されています.複数のパラメータ値が定義され、これらのパラメータ値はすべて使用されなくてもいいです.
@RequestMapping(value = "/ex/bars", params = { "id", "second" })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") long id) {
    return "Narrow Get a specific Bar with id=" + id;
}
もちろん、URIをお願いします.
http://localhost:8080/spring-rest/ex/bars?id=100&second=something
常に最適なマッチングにマッピングされます.すなわち、範囲が小さいマッチングです.つまり、idとsecondパラメータのマッチングを定義します.
6.Request Mapping Corner Cases 6.1.@Request Mapping–multiple paths mapped to the same controller method
一つの@Request Mappingパス値は通常、一つのcontroller方法に対応していますが、これは良い習慣です.しかし、厳密な規定ではありません.いくつかのカラムに対して複数の要求を同一の方法にマッピングする必要があります.このようなカラムに対して、@Request Mappingのvalue属性は複数のマッピングを受けています.一つだけではありません.
@RequestMapping(value = { "/ex/advanced/bars", "/ex/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
    return "Advanced - Get some Foos or Bars";
}
この2つのcurlコマンドは同じ方法にアクセスします.
curl-ihttp://localhost:8080/spring-rest/ex/advanced/foos
curl-ihttp://localhost:8080/spring-rest/ex/advanced/bars
6.2.@Request Mapping–multiple HTTP request methods to the same controller method
異なるHTTP要求動作による複数の要求は、同じcontroller方法にマッピングされ得る.
@RequestMapping(value = "/ex/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
    return "Advanced - PUT and POST within single method";
}
curlを使って、この2つは同じ方法にアクセスします.
curl-i-X POSThttp://localhost:8080/spring-rest/ex/foos/multiiple
curl-i-X PUThttp://localhost:8080/spring-rest/ex/foos/multiiple
6.3.@Request Mapping–a fallback for all requests
特定のHTTP方法を用いて、すべての要求に対して簡単な処理を行う.
@RequestMapping(value = "*")
@ResponseBody
public String getFallback() {
    return "Fallback for GET Requests";
}
またはすべての要求:
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST ... })
@ResponseBody
public String allFallback() {
    return "Fallback for All Requests";
}
7.Spring Configration
Spring MVCの配置は非常に簡単です.私たちのFooControllerが下のパッケージに定義されていることを考慮してください.
package org.baeldung.spring.web.controller;
 
@Controller
public class FooController { ... }
Spring 3.1からスタートします.私たちはこのcontrollerをスキャンするために、MVC全体と構成経路をサポートするために@Configration類だけが必要です.
@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.spring.web.controller" })
public class MvcConfig {
    //
}
8.コンサート
この文章はSpring中の@Request Mappingの注釈に集中しています.簡単な使用を検討してください.HTTPヘッダのマッピングは@PathVarableバインディング部分のURIとURIパラメータと@Request Paramを処理します.