【问题标题】:How/Why does parameter binding work without @RequestParam?没有@RequestParam,参数绑定如何/为什么起作用?
【发布时间】:2021-08-08 04:00:21
【问题描述】:

我有一个这样声明的端点

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

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

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

但是如果我像这样对@RequestParam 不关心

@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,因为我没有使用单个参数,但我不明白为什么它根本没有任何注释就可以工作。它怎么知道绑定它?此功能是否记录在任何地方?

【问题讨论】:

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


    【解决方案1】:

    参数不加注解谁负责解决?

    这是RequestParamMethodArgumentResolver 文档说:

    解析带有@RequestParam 注释的方法参数,参数为 结合 Spring 的 MultipartResolver 键入 MultipartFile 抽象和 javax.servlet.http.Part 类型的参数 结合 Servlet 3.0 多部分请求。这个解析器可以 也可以在默认解析模式下创建,其中简单类型(int, long 等)未使用 @RequestParam 注释的也被视为 使用从参数派生的参数名称请求参数 姓名。如果方法参数类型是 Map,则在 注解用于解析请求参数的String值。这 然后通过类型转换将值转换为 Map 假设 合适的 Converter 或 PropertyEditor 已注册。或者如果一个 请求参数名称未指定 RequestParamMapMethodArgumentResolver 用于提供 以map的形式访问所有请求参数。

    调用 WebDataBinder 以将类型转换应用于已解析 请求头值与方法参数类型不匹配。

    这就是它起作用的原因。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2010-10-26
      • 2021-07-05
      相关资源
      最近更新 更多