SpringMVC的常用注解和使用场景
# SpringMVC的常用注解和使用场景
# 一、常用注解
@Controller
Spring定义的,作用就是标明这是一个controller类
@RestController
@Controller+@ResponseBody的组合,目前大多数项目前后端分离,因此更多使用RestController
@RequestMapping
可以作用在类或者方法上面,做请求的URL跟我们controller或者方法的映射关系
@GetMapping:
请求方式为GET
@PostMapping
请求方式为POST
@RequestParam
做请求参数的匹配,当请求参数名称跟我们方法的参数名不一致的时候,可以做匹配
@RequestBody
接收请求中的参数信息,一般来说,接收一个集合或数组,或者以post方式提交的数据
@PathVariable
获取URL中携带的参数值,处理RESTful风格的路径参数
@CookieValue
获取浏览器传递cookie值
@RequestHeader
获取请求头中的信息
@ResponseBody
改变返回逻辑视图的默认行为,返回具体的数据,比如json
# 二、示例
@RestController
@RequestMapping("/persons")
public class PersonController {
@RequestMapping(value = "/getPerson1", method = RequestMethod.GET)
public Person getPerson1(@RequestParam("id") Long id) {
return new Person("Jack");
}
@GetMapping("/{id}")
public Person getPerson2(@PathVariable Long id,@RequestHeader(value="token",required = false) String token) {
System.out.println("id = " + id + ", token = " + token);
return new Person("Jack");
}
@PostMapping("/add")
public void add(@RequestBody Person person) {
//...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20