1. 路径开头的”/“可有可无
无论@RequestMapping是加在类上,还是方法上,开头的”/“可有可无,习惯加上”/“1
2
3// 以下两个mapping是等价的
("hello")
("/hello")
2. 两个方法不能处理同一请求
1 | ("/hello") |
3. @RequestMapping 来处理多个 URI
你可以将多个请求映射到一个方法上去,只需要添加一个带有请求路径值列表的 @RequestMapping 注解就行了
1 | (value = {"/user", "/user*", "**/hello"}) |
4. @RequestMapping标注在类上与方法上
@RequestMapping标注在类上,可以为当前类所有方法的请求地址指定一个基准路径
1 | ("/user") // 注意路径开头的"/"省略,即 "/user" 可简写为"user" |
5. Ant风格路径通配符映射请求
| Wildcard | Description |
|---|---|
? |
匹配任意单字符 |
* |
匹配0或者任意数量的字符,不包含/ |
** |
匹配0或者更多数量的目录,不包含/ |
1 | // 匹配/user, /user11, 但无法匹配/user11/22, /user/11 |
需要注意的是,路径匹配遵循最长匹配原则(has more characters)1
2
3// 例如同时存在以下映射,"/user/aa"优先匹配"/user/*"
("/**/user/*")
("/user/*")
6. @RequestMapping的各种参数
6.1. method限制请求类型
请求可取的值1
2
3public enum RequestMethod {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}
1 | // 默认处理所有类型的请求 |
6.2. params限制请求参数
注意各种URL中是否带有某个参数的区别1
2
3
4http://localhost:8080/user?username username值为空串
http://localhost:8080/user?username= username值为空串
http://localhost:8080/user?username=123 username值为123
http://localhost:8080/user username值为null
params参数限定1
2
3
4
5
6
7
8
9
10// 参数必须带有username
(value = "/user", params = {"username"})
// 参数必须不带有username
(value = "/user", params = {"!username"})
// 参数必须带有username,且值=123
(value = "/user", params = {"username=123"})
// 参数可以不带有username,或者有username但是值不是123
(value = "/user", params = {"username!=123"})
// 多参数限定
(value = "/user", params = {"username","!aaa", "bbb=123", "ccc!=456"})
6.3. headers限定请求头
1 | // 限定content-type |
6.4. consumes限定请求头中的Content-Type
6.5. produces给响应头设置Content-Type
7. 组合注解
Spring 4.3 引入了方法级注解的变体,也被叫做 @RequestMapping 的组合注解。组合注解可以更好的表达被注解方法的语义。它们所扮演的角色就是针对 @RequestMapping 的封装,而且成了定义端点的标准方法
例如,@GetMapping 是一个组合注解,它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式
方法级别的注解变体有如下几个:
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
1 |
|