gpt4 book ai didi

spring - @RequestHeader 请求参数和值所需的属性行为

转载 作者:行者123 更新时间:2023-12-02 17:27:03 29 4
gpt4 key购买 nike

我们可以使用@RequestHeader 强制 header 参数而不是值吗?

例如,如果我们使用,

@RequestHeader(value = "abc", required = true) 

参数和它的值都必须存在。

编辑:假设我调用一些 rest api 上面的请求 header 参数带有“abc”但没有值。所以在这种情况下,我能够成功调用 rest api,因为我已经使用“abc” header 参数调用,即使我没有输入值。由于一些治理工具规则,我需要有一个特定的 header 参数,但我不想强制用户输入任何值。

最佳答案

Spring 5.2 及更低版本

@RequestHeader 没有提供额外的工具来检查参数的值是强制性的,即不为空。

下面是根据 Spring Doc 提供的可用字段

  • defaultValue:用作回退的默认值。
  • name:要绑定(bind)的请求 header 的名称。
  • required:header是否必填;允许空值
  • value:name() 的别名

所以你可以做的是在@RequestHeader 的帮助下读取参数或注入(inject) HttpServletRequest 请求,通过 request.getHeader(...) 读取并检查 Controller 方法内部是否存在值,然后可以调用方法执行必要的逻辑。

尽管您可以借助所需属性确保参数存在,例如@RequestHeader(value = "Authorization", required = true) String authorization).

Spring 5.3+

required 字段被收紧了,属性和值都应该存在。来自release notes :

The @RequestHeader annotation detect a null conversion result value and treat it as missing. In order to allow an empty value to be injected as a null argument, either set required=false on the argument annotation, e.g. @RequestParam(required=false), or declare the argument as @Nullable.

关于spring - @RequestHeader 请求参数和值所需的属性行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959656/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com