我如何能够自动验证@ResponseBody(在我的情况下是SomePojoInterface类)(通过JSR-303验证)。很高兴,如果验证失败,处理程序将抛出一个Exception
,可以在一些@ControllerAdvice
带注释的类中处理。
到目前为止我的代码。
@RestController
public class MyRestController {
@GetMapping(value = "validate", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
protected SomePojo validateResponse() {
return new SomePojo();
}
}
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.XXX)
@ExceptionHandler(MyResponseValidationException.class)
public void handleResponseValidationException() {
// ...
}
}
public class SomePojo implements SomePojoInterface {
@NotNull
private String someValue;
// getter / setter
}
答案 0 :(得分:0)
如果你注释了你的类SomePojo,那么:
@GetMapping(value = "validate", produces = MediaType.APPLICATION_JSON_VALUE)
protected SomePojo validateResponse() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
SomePojo somePojo = new SomePojo(null);
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(somePojo);
// Other stuff
}
@Valid注释用于请求。来自docs的更多示例。我不确定你要验证的是什么
答案 1 :(得分:0)
我设法通过@RestControllerAdvice
public class RestPostProcessingAdvice implements ResponseBodyAdvice<SomePojoInterface> {
@Inject
private Validator validator;
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
if(doSomeChecksIfEligiable(returnType, converterType)) {
return true;
}
return false;
}
@Override
public SomePojoInterface beforeBodyWrite(SomePojoInterface body, MethodParameter returnType,
MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(body);
if(constraintViolations.size() > 0) {
response.setStatusCode(HttpStatus.XXX);
LOG.fatal("Sorry, I'm sending crap");
}
return body;
}
}
实现了这一目标。
Exception
请注意,抛出@ExceptionHandler
并将其捕获到@ResponseBody
中@RestControllerAdvice
中发送相同(mofified)对象的 UPDATE Y SET Y.yVAL=X.xVAL WHERE Y.yID = X.xID;
可能会导致无限循环,因为该对象将再次检查items=new JSONObject();
。