Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 529
Edward Q. Bridges Avatar asked Dec 23 '22 08:12

Edward Q. Bridges


1 Answers

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.

like image 87
oberlies Avatar answered Dec 28 '22 07:12

oberlies