Spring Boot REST @RequestParam未经过validation

我从网上尝试了很多例子,但是无法让Springvalidation我的查询字符串参数。 它似乎没有执行REGEX / fail。

package my.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import javax.validation.constraints.Pattern; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController public class MyController { private static final String VALIDATION_REGEX = "^[0-9]+(,[0-9]+)*$"; @RequestMapping(value = "/my/{id}", method = GET) public myResonseObject getMyParams(@PathVariable("id") String id, @Valid @Pattern(regexp = VALIDATION_REGEX) @RequestParam(value = "myparam", required = true) String myParam) { // Do Stuff! } } 

目前的行为

 PASS - /my/1?myparam=1 PASS - /my/1?myparam=1,2,3 PASS - /my/1?myparam= PASS - /my/1?myparam=1,bob 

期望的行为

 PASS - /my/1?myparam=1 PASS - /my/1?myparam=1,2,3 FAIL - /my/1?myparam= FAIL - /my/1?myparam=1,bob 

谢谢

您需要将@Validated添加到您的类中,如下所示:

 @RestController @Validated class Controller { // ... } 

更新

你需要正确配置它..将此bean添加到您的上下文:

 @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); } 

处理exception的示例

 @ControllerAdvice @Component public class GlobalExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public Map handle(MethodArgumentNotValidException exception) { return error(exception.getBindingResult().getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList())); } @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public Map handle(ConstraintViolationException exception) { return error(exception.getConstraintViolations() .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.toList())); } private Map error(Object message) { return Collections.singletonMap("error", message); } } 

你可以试试这个

 @Pattern(regexp="^[0-9]+(,[0-9]+)*$") private static final String VALIDATION_REGEX; 

(注意最终修饰符)或者

  @Pattern() private static final String VALIDATION_REGEX = "^[0-9]+(,[0-9]+)*$"; 

然后从您的方法中删除@Pattern(regexp = VALIDATION_REGEX)并仅保留@Valid注释:

 public myResonseObject getMyParams(@PathVariable("id") String id, @Valid @RequestParam(value = "myparam", required = true) String myParam) { 

你有不正确的正则表达式

 "^[0-9]+(,[0-9]+)*$" 

它永远不会解析

 1,bob 

也许,你需要:

 "^\w+(,\w+)*$" 

如果您还需要解析空行,请使用:

 "^(\w+(,\w+)*)?$"