一、RequestMapping介绍
RequestMapping是Spring MVC框架中最重要的注解的之一,其作用是将HTTP请求映射到控制器的处理方法上。RequestMapping的精髓就在于将URL映射到代码执行上,实现不同的HTTP请求对应不同的方法调用,可以说是Web开发中不可缺少的注解。
二、RequestMapping的用法
RequestMapping注解可以用于类和方法两个级别上,用于类级别上时,表示该类里所有方法的URL都是这个,比如@RestController、@RequestMapping(“/user”),之后提到的所有URL都是在/user之后拼接的。
RequestMapping注解的value属性来指定处理请求的URL,请求可以设置一个或多个参数,如value和method等等。属性值通过花括号括起来,并用逗号分隔,如:@RequestMapping(value={“”,””},method=RequestMethod.GET)。
三、RequestMapping的属性
1. value/ path :用于指定请求的实际地址,指定的地址可以是URI Template 模式
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET) public void getUser(@PathVariable Long id, ModelMap modelMap) { // get some user data }
2. method:用于指定请求的method类型,注意:可以是POST、GET、PUT、DELETE等
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST) public void updateUser(@PathVariable Long id, @RequestBody User user) { // update user data }
3. params:用于指定request中必须包含某些参数值是,才能被匹配上,如:”params= {“name”}”表示请求中必须包含name参数
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST,params= {"name"}) public void updateUser(@PathVariable Long id, @RequestBody User user) { // update user data }
4. headers:用于指定request中必须包含某些指定的HTTP请求头是,才能被匹配上,如:”headers = {“content-type=text/*”}”表示请求中必须包含content-type为text/*类型的请求头
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST,headers = {"content-type=text/*"}) public void updateUser(@PathVariable Long id, @RequestBody User user) { // update user data }
5. consumes:用于指定处理请求的提交内容类型(Content-Type),如:”consumes = {“text/plain”, “application/*”}”,表示处理请求的提交内容类型必须是text/plain或者是application/*
@RequestMapping(value = "/user/{id}", method = RequestMethod.POST, consumes = {"text/plain", "application/*"}) public void updateUser(@PathVariable Long id, @RequestBody User user) { // update user data }
6. produces:用于指定返回的内容类型,仅当request请求头中的(Accept)类型和produces指定的类型相同时,才会返回;如:produces={“application/xml”, “application/json”},表示返回的内容类型必须是application/xml或者是application/json
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {"application/xml", "application/json"}) public @ResponseBody User getUser(@PathVariable Long id) { // get user data }
四、RequestMapping示例
示例展示如何通过RequestMapping注解实现get请求和post请求的映射。
1. get请求映射:
@RequestMapping(method = RequestMethod.GET, value = "/healthz") public ResponseEntity checkHealth() { return ResponseEntity.status(HttpStatus.OK).body("OK"); }
上述代码将get请求的URI”/healthz”映射到了checkHealth方法,该方法返回一个字符串”OK”并将状态设置为HttpStatus.OK。
2. post请求映射:
@PostMapping(path = "/register") public ResponseEntity createUser(@RequestBody RegisterRequest request) { //create user logic... return ResponseEntity.status(HttpStatus.OK).body("User created with id:" + userId); }
上述代码将post请求的URI”/register”映射到了createUser方法,该方法创建了一个用户,并将其ID返回。
五、总结
RequestMapping作为Spring MVC框架中最重要的注解之一,是将HTTP请求映射到控制器的处理方法上的重要手段之一。其通过各种不同属性的设置,实现了请求到方法调用的转换,为Web应用开发提供了便利。
原创文章,作者:UYKXF,如若转载,请注明出处:https://www.506064.com/n/370709.html