开发者

Validate request headers with Spring validation framework

Is it possible 开发者_开发百科to use the Spring validation framework with Spring MVC to validate the presence and value of an HTTP request header?


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.

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)

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

  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
    

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.


I don't see how this would be possible, since the validation framework only operates on your domain objects, not on the HTTP request itself. Specifically, the Validator interface doesn't specify any methods that take the HttpServletRequest object, which is what you'd need to have access to in order to grab the headers and test them.

Using the validation framework feels like the wrong solution to whatever problem you're trying to solve, especially since it's hard to know how there'd be a unique HTTP request header for a given form submission. Are you looking to test for an HTTP header that should always be present in requests to your app? Then you might want to consider implementing a HandlerInterceptor, which will intercept and process all requests to pages that you've mapped in any HanderMappings. Are you looking to test for an HTTP header that should always be present in any page view of your app? Then you'd want to implement a Filter, which operates outside of the context of Spring MVC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜