@RequestHeader 请求参数和值的必需属性行为 [英] @RequestHeader required property behavior for request paramter and value

查看:77
本文介绍了@RequestHeader 请求参数和值的必需属性行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can we make a header parameter mandatory but not the value using @RequestHeader?

例如,如果我们使用,

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

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

both parameter and it value has to be there.

假设我调用了一些rest api,上面的请求头参数带有abc"但没有值.因此,在这种情况下,我能够成功调用其余 api,因为即使我没有输入值,我也使用abc"标头参数进行了调用.由于某些治理工具规则,我需要有一个特定的标题参数,但我不想强制用户输入任何值.

Suppose i call some rest api has above request header param with "abc" but no value. So in this case i am able to invoke the rest api successfully since i have invoke with "abc" header param even i did not enter a value to it. Due to some governance tool rule, i need to have a specific header param but i dont want force user to enter any value.

推荐答案

目前 @RequestHeader 没有提供额外的工具来检查参数的值是否为强制值,即非空.

At present @RequestHeader doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.

>

下面给出了根据 Spring 文档

  • defaultValue:用作后备的默认值.
  • name:要绑定到的请求头的名称.
  • required:是否需要标头.
  • value:name() 的别名
  • defaultValue: The default value to use as a fallback.
  • name: The name of the request header to bind to.
  • required: Whether the header is required.
  • value: Alias for name()

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

So what you can do is read the parameter either with the help of @RequestHeader or inject a HttpServletRequest request, read by request.getHeader(...) and check inside the controller method if the value exists and then can call methods to perform the necessary logic.

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

Although you can make sure that the parameter exists with the help of required attribute for eg @RequestHeader(value = "Authorization", required = true) String authorization)

这篇关于@RequestHeader 请求参数和值的必需属性行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆