@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一。这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
Request Mapping 基础用法
下面是一个同时在类和方法上应用了 @RequestMapping 注解的示例:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping("/")
String get() {
//mapped to hostname:port/home/
return "go to home";
}
@RequestMapping("/index")
String index() {
//mapped to hostname:port/home/index/
return "go to index";
}
}
如上述代码所示,到 /home 的请求会由 get() 方法来处理,而到 /home/index 的请求会由 index() 来处理。
@RequestMapping 可以处理多个 URI
@RestController
@RequestMapping({"/","/index","index.html"} )
public class IndexController {
String indexMultipleMapping() {
return "index";
}
}
如上述代码所示,到 /,/index,/index.html 的请求都会跳转到index页面
@RequestMapping指定请求的method类型
@RequestMapping(value = "/list" , method = RequestMethod.POST)
public Str post(){
return post;
}
}
post请求为例,只有post请求才会经过改方法
@RequestMapping指定params内容
//设定必须包含username 和age两个参数,且age参数不为10 (可以有多个参数)
@RequestMapping(value = "/list" , method = RequestMethod.POST,params = { "username","age!=10" })
public JSONObject list(@PathVariable String communityId) {
JSONObject object = new JSONObject();
object.put("communityId",communityId);
return object;
}
指定request中必须包含某些参数值时,才让该方法处理。