Spring Boot REST @RequestParam not being Validated

前端 未结 3 646
慢半拍i
慢半拍i 2020-12-13 09:58

I have tried a number of examples from the net and cannot get Spring to validate my query string parameter. It doesn\'t seem execute the REGEX / fail.

packag         


        
相关标签:
3条回答
  • 2020-12-13 10:31

    You need add @Validated to your class like this:

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

    UPDATE:

    you need to configure it properly.. add this bean to your context:

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

    Example to handle 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);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 10:35

    You can try this

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

    (pay attention for the final modifier) or else

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

    And then remove @Pattern(regexp = VALIDATION_REGEX) from your method and keep only the @Valid annotation:

    public myResonseObject getMyParams(@PathVariable("id") String id, @Valid @RequestParam(value = "myparam", required = true) String myParam) {
    
    0 讨论(0)
  • 2020-12-13 10:46

    You have incorrect regex

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

    It will never parse

    1,bob
    

    Maybe, you need:

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

    And if you need to parse also an empty line, use:

    "^(\w+(,\w+)*)?$"
    
    0 讨论(0)
提交回复
热议问题