你可以使用這樣的: 使用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));
}
}
}
你給的鏈接說: 「如果PathVariable參數驗證失敗,那麼Spring將錯誤自動添加到請求的BindingResult,你不需要做你自己「。 這是否意味着@PathVariable params上的bean驗證是可能的?它沒有清楚地說出它是否可能。可能是我誤解了。我已經按照建議的方式嘗試過了,但是當驗證失敗時,綁定結果沒有任何錯誤。 – Grover