使用Spring验证框架验证请求标头 [英] Validate request headers with Spring validation framework
问题描述
是否可以将带有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
- 将
@Validated
添加到控制器类.在实施此功能之前,这是一种解决方法. >
-
将JSR-303批注添加到请求标头参数中,例如
- Add
@Validated
to the controller class. This is a workaround needed until this feature is implemented. 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屋!