1) 普通path路径@RequestMapping(value = "/foos")@ResponseBodypublic String getFoosBySimplePath() { return "Get some Foos";}2) 指定RequestMethod.POST@RequestMapping(value = "/foos", method = RequestMethod.POST)@ResponseBodypublic String postFoos() { return "Post some Foos";}3) 指定http请求头@RequestMapping(value = "/foos", headers = "key=val")@ResponseBodypublic String getFoosWithHeader() { return "Get some Foos with Header";}其中在headers可以跟多个了,如:RequestMapping(value = "/foos", headers = { "key1=val1", "key2=val2" })@ResponseBodypublic String getFoosWithHeaders() { return "Get some Foos with Header";}4)@RequestMapping中的新的PRoduct和consume. 在spring 3.0中,可以指定请求头的media格式,如:@RequestMapping(value = "/foos", method = RequestMethod.GET, headers = "Accept=application/json")@ResponseBodypublic String getFoosAsJsonFromBrowser() { return "Get some Foos with Header Old";}如果在3.1中,则有新的 produces和consume的属性了,如:@RequestMapping(value = "/foos", method = RequestMethod.GET, produces = "application/json")@ResponseBodypublic String getFoosAsJsonFromREST() { return "Get some Foos with Header New";}如果用3.1,但依然用旧的方式,则旧的方式的请求都会自动变成produces和consume了;@RequestMapping(value="/testMsgConverter",consumes="text/plain",produces="application/json") 表示handlermethod接受的请求的header中的 Content-Type为text/plain; Accept为application/json 5) @PathVariable 1 单一的@RequestMapping(value = "/foos/{id}")@ResponseBodypublic String getFoosBySimplePathWithPathVariable(@PathVariable("id") long id) { return "Get a specific Foo with id=" + id;} 2 多个@RequestMapping(value = "/foos/{fooid}/bar/{barid}")@ResponseBodypublic String getFoosBySimplePathWithPathVariables(@PathVariable long fooid, @PathVariable long barid) { return "Get a specific Bar with id=" + barid + " from a Foo with id=" + fooid;}
3 也支持正则表达式 @RequestMapping(value = "/bars/{numericId:[//d]+}")@ResponseBodypublic String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) { return "Get a specific Bar with id=" + numericId;}参数只接受数字
6) requestparam
@RequestMapping(value = "/bars")@ResponseBodypublic String getBarBySimplePathWithRequestParam(@RequestParam("id") long id) { return "Get a specific Bar with id=" + id;}@RequestMapping(value = "/bars", params = "id")@ResponseBodypublic String getBarBySimplePathWithExplicitRequestParam(@RequestParam("id") long id) { return "Get a specific Bar with id=" + id;}7) RequestMapping支持多个映射路径映射到同一个controller,如:@RequestMapping(value = { "/advanced/bars", "/advanced/foos" })@ResponseBodypublic String getFoosOrBarsByPath() { return "Advanced - Get some Foos or Bars";}curl -i http://localhost:8080/spring-mvc/advanced/fooscurl -i http://localhost:8080/spring-mvc/advanced/bars甚至还支持put,post同时请求,如:@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })@ResponseBodypublic String putAndPostFoos() { return "Advanced - PUT and POST within single method";}
新闻热点
疑难解答