【六袆-Spring】Spring @RequestParam批注的解释

1.设置指定请求参数名称

 

在前面的示例中,变量名称和参数名称相同。

有时候,我们希望它们有所不同。或者,如果我们不使用Spring Boot,则可能需要进行特殊的编译时配置,否则参数名称实际上将不在字节码中。

但是很好的是,我们可以使用name属性配置  @RequestParam名称:

1
2
3
4
5
@PostMapping("/api/foos")
@ResponseBody
public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {
    return "ID: " + fooId + " Name: " + name;
}

我们还可以执行  @RequestParam(value =“ id”)或仅执行@RequestParam(“ id”)。


2.设置可选的请求参数

 

 默认情况下,需要使用@RequestParam注释的方法参数  。

这意味着,如果请求中不存在该参数,则会收到错误消息:

1
2
3
4
GET /api/foos HTTP/1.1
-----
400 Bad Request
Required String parameter 'id' is not present

但是,我们可以将@RequestParam配置为可选,并具有必填 属性:

 
1
2
3
4
5
@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam(required = false) String id) {
    return "ID: " + id;
}

在这种情况下,两者:

1
2
3
http://localhost:8080/api/foos?id=abc
----
ID: abc

1
2
3
http://localhost:8080/api/foos
----
ID: null

将正确调用该方法。

如果未指定参数,则方法参数绑定为null

 

posted @ 2022-04-26 00:54  你好,Alf  阅读(8)  评论(0编辑  收藏  举报