How to validate the size of @RequestParam of type List

前端 未结 3 1044
走了就别回头了
走了就别回头了 2021-01-13 21:53

I\'m creating a Spring-Boot microservice REST API that expects @RequestParam of type List. How can I validate that the list contains

相关标签:
3条回答
  • 2021-01-13 22:17

    If you're using method argument validation, you should annotate your controller with @Validated, as mentioned by the documentation:

    To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation. (Optionally, you can also declare the validation groups to use.) See the MethodValidationPostProcessor javadoc for setup details with the Hibernate Validator and Bean Validation 1.1 providers.

    That means you should change your code to:

    @Validated // Add this
    @RestController
    public class MyApi {
        // ...
    }
    

    After that, it will throw a ContraintViolationException if the validation doesn't match.

    Be aware though, since you only have a @Size() annotation, if you don't provide a programEndTime, the collection will be null and that will be valid as well. If you don't want this, you should add a @NotNull annotation as well, or remove the required = false value from @RequestParam.

    You can't use the BindingResult though to retrieve the errors, as that only works for model attributes or request bodies. What you can do, is define an exception handler for ConstraintViolationException:

    @ExceptionHandler(ConstraintViolationException.class)
    public void handleConstraint(ConstraintViolationException ex) {
        System.out.println("Error");
    }
    
    0 讨论(0)
  • 2021-01-13 22:19

    As per Bean Validator 2.0, Hibernate Validator 6.x, you can use constraints directly on parameterized type.

    @GetMapping(path = "/myApi", produces = { APPLICATION_JSON_VALUE })
    public ResponseEntity<List<MyObject>> getSomething(@RequestParam(value = "programEndTime", required = false) List<@Size(min = 1, max = 2) String> programEndTimes)
    

    For more information, check out Container element constraints.

    0 讨论(0)
  • 2021-01-13 22:32

    You can use a Class and @RequestBody for parameter validation, which is successful like me.

    public class Test {
        @Size(min = 1 , max = 5)
        private List<String> programEndTime;
    
        public List<String> getProgramEndTime() {
            return programEndTime;
        }
    
        public void setProgramEndTime(List<String> programEndTime) {
            this.programEndTime = programEndTime;
        }
    }
    
        @PostMapping("test")
        public void test( @Valid   @RequestBody Test test,
                         BindingResult result){
            if (result.hasErrors()) {
                System.out.println("Error");
            } else {
                System.out.println("OK");
            }
            System.out.println(",.,.");
        }
    
    0 讨论(0)
提交回复
热议问题