Java 如何验证RestAPI控制器终结点的RequestHeader
我已经编写了一个控制器类,其端点接受头作为其请求的一部分Java 如何验证RestAPI控制器终结点的RequestHeader,java,rest,spring-boot,bean-validation,request-headers,Java,Rest,Spring Boot,Bean Validation,Request Headers,我已经编写了一个控制器类,其端点接受头作为其请求的一部分 @RestController @RequestMapping("<mapping-path>") public class MyController { ... @GetMapping("<path-to-the-endpoint>") public MyObject getMyObject(@RequestHeader("headerName") String headerName) { //do so
@RestController
@RequestMapping("<mapping-path>")
public class MyController {
...
@GetMapping("<path-to-the-endpoint>")
public MyObject getMyObject(@RequestHeader("headerName") String headerName) {
//do something with the header here
}
...
}
@RestController
@请求映射(“”)
公共类MyController{
...
@GetMapping(“”)
公共MyObject getMyObject(@RequestHeader(“headerName”)字符串headerName){
//在这里对标题做些什么
}
...
}
端点工作正常,但我想在提供带有null值的头时测试其行为。我还希望对
getMyObject
方法进行编码,以防止将空值传递到头中,并返回警告,说明头字段不能为空。我尝试使用一个集成测试来测试这一点,该测试在端点上使用了一个MockMvc
get()
,但是如果我在get请求中向报头授予一个空值,测试就会失败,因为它说“值不能为空”。这里可以使用JSR-303验证方法吗?i、 e.@Valid
和@NotNull
?我认为参数化请求头应该适合您
尝试这样声明您的方法
@GetMapping("<path-to-the-endpoint>")
public MyObject getMyObject(@RequestHeader(value="headerName") String headerName) {
//do something with the header here
}
post("/your end point").header("headerName", "userId")