Original link: http://www.cnblogs.com/AloneSword/p/4099142.html
Introduction to spring3's restful API RequestMapping
In spring mvc @RequestMapping is a method of mapping web requests to controllers.
1.RequestMapping Basic Example
The most direct way to map http requests to controller methods
1.1 @RequestMapping by Path
@RequestMapping(value = "/foos")
@ResponseBody
public String getFoosBySimplePath() {
return "Get some Foos";
}
You can pass the following The way to test: curl -i http://localhost:8080/springmvc/foos
1.2 @RequestMapping – the HTTP Method, we can add restrictions on the http method
@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
When the header of the request contains a certain key value
@RequestMapping(value = "/foos", headers = "key=val")
@ResponseBody
public String getFoosWithHeader() {
return "Get some Foos with Header";
}
When multiple header fields meet the conditions
@RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })
@ResponseBody
public String getFoosWithHeaders() {
return "Get some Foos with Header";
}
Tested by curl -i -H "key:val" http://localhost:8080/springmvc/foos.
2.2 @RequestMapping and Accept headers
@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测试
In spring 3.1, the @RequestMapping annotation has two attributes: produces and consumes instead of the accept header
@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 can support multiple
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
Currently two methods cannot be mapped to the same request at the same time, otherwise the following exception will occur
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;
}
Try it through curl http://localhost:8080/springmvc/foos/1
If the parameter name is the same as the url parameter name, it can be omitted as
@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;
}
This url matches: http://localhost:8080/springmvc/bars/1
but this does not match: http://localhost:8080/springmvc/bars/abc
4.RequestMapping with Request Parameters
We can use the @RequestParam annotation to extract request parameters
such as 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;
}
We can define the parameter list through 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;
}
For example, http://localhost:8080/springmvc/bars?id=100&second=something will match the best matching method, which will be mapped to the following.
5.RequestMapping Corner Cases
5.1 @RequestMapping multiple paths are mapped to the same method of the same controller
@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })
@ResponseBody
public String getFoosOrBarsByPath() {
return "Advanced - Get some Foos or Bars";
}
The following two urls will match the same a method
curl -i http://localhost:8080/springmvc/advanced/foos
curl -i http://localhost:8080/springmvc/advanced/bars
5.2@RequestMapping Multiple http methods are mapped to the same method of the same controller
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
return "Advanced - PUT and POST within single method";
}
The following two urls will match the above method
curl -i -X POST http://localhost:8080/springmvc/foos/multiple
curl -i -X PUT http://localhost:8080/springmvc/foos/multiple
5.3 @RequestMapping matches all methods
@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 {
//
}
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class SubsystemDemoApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SubsystemDemoApplication.class, args); } }
All examples can be seen from here https://github.com/eugenp/tutorials/tree/master/springmvc