@RestController:验证@ResponseBody(不是@RequestBody)

时间:2017-01-10 16:36:53

标签: spring spring-mvc

我如何能够自动验证@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
}

2 个答案:

答案 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();