java - 如何验证 List 类型的@RequestParam 的大小

标签 java spring-boot spring-web spring-validator

我正在创建一个需要 @RequestParam 的 Spring-Boot 微服务 REST API类型 List<String> .我如何验证列表是否包含最小值和最大值?

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

我还尝试添加 @Valid和一个 BindingResult参数以及 @Size注释没有成功。

我更喜欢使用类似于第一个示例的解决方案,使用 @Size(min=1, max=2)更紧凑,更整洁。这是针对 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")要到达的行,但它实际上被跳过了。

最佳答案

如果您使用方法参数验证,您应该使用 @Validated 注释您的 Controller ,如 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.

这意味着您应该将代码更改为:

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

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

请注意,由于您只有一个 @Size() 注释,如果您不提供 programEndTime,则该集合将为 null 并且这也是有效的。如果您不想这样做,您还应该添加一个 @NotNull 注释,或者从 @RequestParam 中删除 required = false 值。

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

@ExceptionHandler(ConstraintViolationException.class)
public void handleConstraint(ConstraintViolationException ex) {
    System.out.println("Error");
}

关于java - 如何验证 List 类型的@RequestParam 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55372174/

相关文章:

java - Spring boot 2 的 Redshift jdbc 连接配置不起作用

java - 如何成为管理员?页面

java - spring-boot:在哪里定义了生成 jar 文件的设置

java - 如何仅在 mvc 层排除验证属性(并保留数据库层)?

java - 如何防止spring-web的spring-boot自动配置?

java - Spring JPAFailed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Why?'

java - 在通用类中传递 int 数组

java - 使用java swings删除选定的复选框而不使用Jtable/Database

Java交集集合

java - spring.mvc.view.prefix 和 spring.mvc.view.suffix 必须是什么?