1.介绍
学习了解Spring的@RequestParam注解及其属性。
简而言之,可以使用@RequestParam从请求中提取查询参数,表单参数甚至文件。
2.一个简单的映射
@GetMapping("/api/foos")
public String getFoos(@RequestParam String id) {
return "ID: " + id;
}
在上面示例中,使用@RequestParam提取id查询参数。
curl http://localhost:19999/api/foos?id=abc
---
ID: abc
下来在看一下注解的属性:name,value,required和defaultValue。
3.指定请求参数名称
在前面的示例中,变量名称和参数名称相同。
有时候,是会有所不同。 或者,如果不使用Spring Boot,则可能需要进行特殊的编译时配置。
可以使用name属性配置@RequestParam名称:
@PostMapping("/api/foos")
public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {
return "ID: " + fooId + " Name: " + name;
}
@RequestParam(value =“id”)或@RequestParam(“id”),都是可以的。
4.可选的请求参数
默认情况下,需要使用@RequestParam注解的方法参数是必须存在的。
如果请求中不存在该参数,则会收到错误消息:
GET /api/foos HTTP/1.1
-----
400 Bad Request
Required String parameter 'id' is not present
可以将@RequestParam配置为可选,并具有必填属性:
@GetMapping("/api/foos")
public String getFoos(@RequestParam(required = false) String id) {
return "ID: " + id;
}
在这种情况下,两个都:
http://localhost:19999/api/foos?id=abc
----
ID: abc
或者
http://localhost:19999/api/foos
----
ID: null
如果未指定参数,则方法参数将绑定为null。
4.1 使用Java 8 Optional
可以将参数包装在Optional中:
@GetMapping("/api/foos")
public String getFoos(@RequestParam Optional<String> id){
return "ID: " + id.orElseGet(() -> "not provided");
}
在这种情况下,不需要指定必需的属性。
如果未提供request参数,则将使用默认值:
http://localhost:19999/api/foos
----
ID: not provided
5.请求设置参数默认值
可以@RequestParam的defaultValue属性给参数设置默认值
@GetMapping("/api/foos")
public String getFoos(@RequestParam(defaultValue = "test") String id) {
return "ID: " + id;
}
就像required = false一样,因为用户不再需要提供参数:
http://localhost:19999/api/foos
----
ID: test
http://localhost:19999/api/foos?id=abc
----
ID: abc
6.映射所有参数
可以使用Map接收所有参数
@PostMapping("/api/foos")
public String updateFoos(@RequestParam Map<String,String> allParams) {
return "Parameters are " + allParams.entrySet();
}
curl -X POST -F 'name=abc' -F 'id=123' http://localhost:19999/api/foos
-----
Parameters are {[name=abc], [id=123]}
7.映射多值参数
单个@RequestParam可以具有多个值:
@GetMapping("/api/foos")
public String getFoos(@RequestParam List<String> id) {
return "IDs are " + id;
}
Spring MVC将映射一个逗号分隔的id参数:
http://localhost:19999/api/foos?id=1,2,3
----
IDs are [1,2,3]
或单独的id参数的列表:
http://localhost:19999/api/foos?id=1&id=2
----
IDs are [1,2]