如何验证类型为List的@RequestParam的大小 [英] How to validate the size of @RequestParam of type List

查看:663
本文介绍了如何验证类型为List的@RequestParam的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Spring-Boot微服务REST API,它期望类型为List<String>@RequestParam.如何验证列表包含最小和最大数量的值?

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?

到目前为止,我已经尝试过使用@Size(min=1, max=2),它也应该支持集合(javax.validation.constraints.Size).

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

我还尝试将@ValidBindingResult参数与@Size注释一起添加,但没有成功.

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

我更喜欢使用类似于第一个示例的解决方案,该解决方案使用更紧凑,更整洁的@Size(min=1, max=2).这是针对Spring-Boot 2.1.2.RELEASE的.

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

我希望能到达System.out.println("Error")行,但实际上已被跳过.

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

推荐答案

如果您正在使用方法参数验证,则应使用@Validated注释控制器,如

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

要有资格通过Spring驱动的方法验证,所有目标类都必须使用Spring的@Validated注释进行注释. (或者,您也可以声明要使用的验证组.)有关Hibernate Validator和Bean Validation 1.1提供程序的设置详细信息,请参见MethodValidationPostProcessor javadoc.

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 {
    // ...
}

此后,如果验证不匹配,它将抛出ContraintViolationException.

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

但是请注意,由于您仅具有@Size()批注,因此,如果不提供programEndTime,则该集合将为null,并且该集合也将有效.如果您不希望这样做,则还应添加@NotNull批注,或从@RequestParam中删除required = false值.

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.

尽管您不能使用BindingResult来检索错误,因为它仅适用于模型属性或请求主体.您可以做的是为ConstraintViolationException定义一个异常处理程序:

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

这篇关于如何验证类型为List的@RequestParam的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆