How to validate the size of @RequestParam of type List

浪尽此生 提交于 2020-01-30 05:18:18

问题


I'm creating a Spring-Boot microservice REST API that expects @RequestParam of type List<String>. How can I validate that the list contains a minimum and a maximum amount of values?

So far I've tried using @Size(min=1, max=2) which is supposed to support collections as well (javax.validation.constraints.Size).

I also tried adding @Valid and a BindingResult parameter along with the @Size annotation without success.

I'd prefer using a solution similar to the first example using @Size(min=1, max=2) which is more compact and neat. This is for Spring-Boot 2.1.2.RELEASE.

@RestController
public class MyApi {

    @GetMapping(value = "/myApi", produces = { APPLICATION_JSON_VALUE })
    public ResponseEntity<List<MyObject>> getSomething(@Valid @RequestParam(value = "programEndTime", required = false) @Size(min = 1, max = 2) List<String> programEndTime, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("Error");
        } else {
            System.out.println("OK");
        }
    }
}

I expect the System.out.println("Error") line to be reached but it's actually skipped.


回答1:


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");
}



回答2:


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(",.,.");
    }



回答3:


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.



来源:https://stackoverflow.com/questions/55372174/how-to-validate-the-size-of-requestparam-of-type-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!