spring - 没有@RequestParam,参数绑定(bind)如何/为什么工作?

标签 spring spring-boot spring-mvc request spring-restcontroller

我有一个这样声明的端点

@GetMapping("/shoebox")
public ResponseEntity<?> find(ShoeBox shoebox) {
    ...
}    

当我发出像 /shoebox?color=blue&size=small 这样的请求时

它正确地将 colorsize 绑定(bind)到一个新的 ShoeBox 对象。

但是如果我像这样使用 @RequestParam delcare

@GetMapping("/shoebox")
public ResponseEntity<?> find(@RequestParam ShoeBox shoebox) {
    ...
}    

然后我得到这个错误

{
    "status": 400,
    "message": "Required request parameter 'shoebox' for method parameter type ShoeBoxis not present",
    "timestamp": 1621373682288,
    "errors": [
        "MissingServletRequestParameterException"
    ]
}

我有点理解为什么它不能与 @RequestParam 一起工作,因为我没有使用单个参数,但我不明白的是为什么它在没有任何注释的情况下工作.它怎么知道要绑定(bind)它?是否在任何地方记录了此功能?

最佳答案

如果参数不加注解,谁来解决?

是这个RequestParamMethodArgumentResolver文档说:

Resolves method arguments annotated with @RequestParam, arguments of type MultipartFile in conjunction with Spring's MultipartResolver abstraction, and arguments of type javax.servlet.http.Part in conjunction with Servlet 3.0 multipart requests. This resolver can also be created in default resolution mode in which simple types (int, long, etc.) not annotated with @RequestParam are also treated as request parameters with the parameter name derived from the argument name. If the method parameter type is Map, the name specified in the annotation is used to resolve the request parameter String value. The value is then converted to a Map via type conversion assuming a suitable Converter or PropertyEditor has been registered. Or if a request parameter name is not specified the RequestParamMapMethodArgumentResolver is used instead to provide access to all request parameters in the form of a map.

A WebDataBinder is invoked to apply type conversion to resolved request header values that don't yet match the method parameter type.

这就是它起作用的原因。

关于spring - 没有@RequestParam,参数绑定(bind)如何/为什么工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67594277/

相关文章:

java - 在 spring boot 中添加外部静态文件(css、js、png ...)

java - Spring REST 服务 : how to configure to remove null objects in json response

spring-boot - RESTful 微服务故障转移和负载平衡

tomcat - 如何使用spring boot将根上下文映射到嵌入式tomcat中的webapp上下文

java - 如何使用参数化注释指定方法及其使用 @Pointcut 的值

spring - 可以通过@RequestBody 以外的方式spring map POST 参数

java - 是否有一个公共(public)位置包含所有 Spring XML 的声明

java - Kotlin + SpringBoot : DI lateinit property service has not been initialized

maven - 记录或打印到 Liquibase 生成的文件 SQL

java - Spring PagedListHolder 获取所有记录