spring3 的restful API RequestMapping介紹


原文鏈接:http://www.javaarch.net/jiagoushi/694.htm

spring3 的restful API RequestMapping介紹

在spring mvc中 @RequestMapping是把web請求映射到controller的方法上。

1.RequestMapping Basic Example
將http請求映射到controller方法的最直接方式
1.1 @RequestMapping by Path

@RequestMapping(value = "/foos")
@ResponseBody
public String getFoosBySimplePath() {
return "Get some Foos";
}

可以通過下面的方式測試: curl -i http://localhost:8080/springmvc/foos

1.2 @RequestMapping – the HTTP Method,我們可以加上http方法的限制

@RequestMapping(value = "/foos", method = RequestMethod.POST)
@ResponseBody
public String postFoos() {
return "Post some Foos";
}

可以通過curl i -X POST http://localhost:8080/springmvc/foos測試。

2.RequestMapping 和http header

2.1 @RequestMapping with the headers attribute
當request的header包含某個key value值時

@RequestMapping(value = "/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
return "Get some Foos with Header";
}

header多個字段滿足條件時

@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
return "Get some Foos with Header";
}

通過curl -i -H "key:val" http://localhost:8080/springmvc/foos 測試。

2.2 @RequestMapping 和Accept頭

@RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public String getFoosAsJsonFromBrowser() {
return "Get some Foos with Header Old";
}
支持accept頭為json的請求,通過curl -H "Accept:application/json,text/html" http://localhost:8080/springmvc/foos測試

在spring3.1中@RequestMapping注解有produces和 consumes 兩個屬性來代替accept頭

@RequestMapping(value = "/foos", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
return "Get some Foos with Header New";
}
同樣可以通過curl -H "Accept:application/json" http://localhost:8080/springmvc/foos測試

produces可以支持多個

@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })

當前不能有兩個方法同時映射到同一個請求,要不然會出現下面這個異常

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 {[/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.

3.RequestMapping with Path Variables
3.1我們可以把@PathVariable把url映射到controller方法
單個@PathVariable參數映射

@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable("id") long id) {
return "Get a specific Foo with id=" + id;
}

通過curl http://localhost:8080/springmvc/foos/1試試
如果參數名跟url參數名一樣,可以省略為

@RequestMapping(value = "/foos/{id}")
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable String id) {
return "Get a specific Foo with id=" + id;
}
3.2 多個@PathVariable

@RequestMapping(value = "/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 http://localhost:8080/springmvc/foos/1/bar/2測試。

3.3支持正則的@PathVariable

@RequestMapping(value = "/bars/{numericId:[\\d]+}")
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
return "Get a specific Bar with id=" + numericId;
}

這個url匹配:http://localhost:8080/springmvc/bars/1
不過這個不匹配:http://localhost:8080/springmvc/bars/abc

4.RequestMapping with Request Parameters

我們可以使用 @RequestParam注解把請求參數提取出來
比如url:http://localhost:8080/springmvc/bars?id=100

@RequestMapping(value = "/bars")
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) {
return "Get a specific Bar with id=" + id;
}

我們可以通過RequestMapping定義參數列表

@RequestMapping(value = "/bars", params = "id")
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") long id) {
return "Get a specific Bar with id=" + id;
}

@RequestMapping(value = "/bars", params = { "id", "second" })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam("id") long id) {
return "Narrow Get a specific Bar with id=" + id;
}

比如http://localhost:8080/springmvc/bars?id=100&second=something會匹配到最佳匹配的方法上,這里會映射到下面這個。

5.RequestMapping Corner Cases

5.1 @RequestMapping多個路徑映射到同一個controller的同一個方法

@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
return "Advanced - Get some Foos or Bars";
}

下面這兩個url會匹配到同一個方法

curl -i http://localhost:8080/springmvc/advanced/foos
curl -i http://localhost:8080/springmvc/advanced/bars

5.2@RequestMapping 多個http方法 映射到同一個controller的同一個方法

@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
return "Advanced - PUT and POST within single method";
}
下面這兩個url都會匹配到上面這個方法

curl -i -X POST http://localhost:8080/springmvc/foos/multiple
curl -i -X PUT http://localhost:8080/springmvc/foos/multiple

5.3@RequestMapping 匹配所有方法

@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";
}

6.Spring Configuration

controller的annotation

@Controller
public class FooController { ... }

spring3.1

@Configuration
@EnableWebMvc
@ComponentScan({ "org.baeldung.spring.web.controller" })
public class MvcConfig {
//
}

可以從這里看到所有的示例https://github.com/eugenp/tutorials/tree/master/springmvc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM