使用Spring验证框架验证请求标头 [英] Validate request headers with Spring validation framework

查看:140
本文介绍了使用Spring验证框架验证请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将带有Spring MVC的Spring验证框架用于验证HTTP请求标头的存在和值?

Is it possible to use the Spring validation framework with Spring MVC to validate the presence and value of an HTTP request header?

推荐答案

要检查请求标头的存在,您不需要验证框架.默认情况下,请求标头参数是必需的,如果请求中缺少必需标头,Spring MVC会自动以400 Bad Request进行响应.

To check the presence of a request header, you don't need the validation framework. Request header parameters are mandatory by default, and if a mandatory header is missing in a request, Spring MVC automatically responds with 400 Bad Request.

因此,以下代码自动检查标头"Header-Name"的存在...

So the following code automatically checks the presence of the header "Header-Name"...

@PostMapping("/action")
public ResponseEntity<String> doAction(@RequestHeader("Header-Name") String headerValue) {
    // ...
}

...,如果标头为可选,则注释应替换为:

... and if the header shall be optional, the annotation would need to be replaced by:

@RequestHeader(name = "Header-Name", required = false)


要检查请求标头的,可以使用Spring验证框架.为此,您需要


To check the value of a request header, the Spring validation framework can be used. To do this, you need to

  1. @Validated添加到控制器类.在实施此功能之前,这是一种解决方法.
  2. >
  3. 将JSR-303批注添加到请求标头参数中,例如

  1. Add @Validated to the controller class. This is a workaround needed until this feature is implemented.
  2. Add the JSR-303 annotation to the request header parameter, e.g.

@RequestHeader("Header-Name") @Pattern(regexp = "[A-Za-z]*") String headerValue

但是请注意,如果标头值无效,则结果为500.检查此问题,以获取有关此情况的正确状态代码(即400)的信息.

Note however that this will result in a 500 in case of an invalid header value. Check this question for how to also get the correct status code (i.e. 400) for this case.

这篇关于使用Spring验证框架验证请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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