【发布时间】:2018-02-23 03:11:16
【问题描述】:
我用 Spring Boot Rest 实现了控制器:
@RestController
@RequestMapping("/example")
public class ExampleController {
@Autowired
private ExampleService exampleService;
@GetMapping("/{id}")
public ExampleResponse getExample(@NotNull @PathVariable("id") String id) {
return exampleService.getExample(id);
}
}
并响应 DTO:
public class ExampleResponse {
@NotNull
private String id;
@NotNull
private String otherStuff;
// setters and getters
}
响应正文未经过验证。我已经用@Valid 对其进行了注释,但null 值仍然通过。请求验证效果很好。
如何验证响应正文?
【问题讨论】:
-
可以分享服务逻辑吗?你是如何在 exampleService 中返回的?
-
这是我第一次听说“响应验证”,通常你只是验证请求。你确定有这样的事情吗?
-
我需要检查是否填写了所有必需的值。我可以使用“@Autowired Validator 验证器”或在服务中明确检查它们,但如果有其他方法可以做到这一点,我会感兴趣。
-
好吧,撇开您这样做的原因,您可以在返回之前手动验证响应,例如以下链接应该会有所帮助:stackoverflow.com/questions/19190592/…
-
你想达到什么目的?是否应省略空字段,控制器是否应返回不同的响应(4xx/5xx)?如果您应该返回不同的响应,请使用手动验证对象,如果不应序列化空字段,请使用杰克逊注解省略空字段
标签: java spring validation spring-boot spring-rest