您可以像这样使用:org.springframework.validation.annotation.Validated
用于有效RequestParam
或PathVariable
。
*
* Variant of JSR-303's {@link javax.validation.Valid}, supporting the
* specification of validation groups. Designed for convenient use with
* Spring's JSR-303 support but not JSR-303 specific.
*
step.1 初始化ValidationConfig
@Configuration
public class ValidationConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
return processor;
}
}
step.2 添加@Validated
到您的控制器处理程序类,如:
@RequestMapping(value = "poo/foo")
@Validated
public class FooController {
...
}
step.3 添加validators
到您的处理程序方法:
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public ResponseEntity<Foo> delete(
@PathVariable("id") @Size(min = 1) @CustomerValidator int id) throws RestException {
// do something
return new ResponseEntity(HttpStatus.OK);
}
最后一步。将异常解析器添加到您的上下文中:
@Component
public class BindExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex.getClass().equals(BindException.class)) {
BindException exception = (BindException) ex;
List<FieldError> fieldErrors = exception.getFieldErrors();
return new ModelAndView(new MappingJackson2JsonView(), buildErrorModel(request, response, fieldErrors));
}
}
}