首页 > 解决方案 > Springboot 请求参数的 Bean 验证

问题描述

我有一个用例,其中我们在 REST 控制器中传递了多个参数,并且必须验证参数是否为空,以及一些自定义验证。此外,对于某些参数,过滤器选项支持startswith、endswith。我能够验证第一个过滤级别的参数,但无法使其适用于下一个过滤级别。例如:查询字符串为 filter.firstname 并且支持可选的startswith 和endswith。有人可以通过提供一些建议来帮助我在有人传递 filter.firstname 或 filter.firstname.startswith 以获取非空值时如何验证参数吗?

这是控制器的示例代码。

 @GetMapping()
    public CustomerResponseData findCustomers(@Valid FilterCustomer filter, HttpServletRequest request)


public class FilterCustomer {

    @Valid
    private FilterCustomerCriteria filter;

}


public class FilterCustomerCriteria {

    @NotBlank
    private String firstname;

    @NotBlank
    private String lastname;
}


public class FilterCustomerFinerCriteria {

    @NotBlank
    private String startswith;

    @NotBlank
    private String endswith;
}```

标签: javaspring-boot

解决方案


如果我理解正确,您会说验证框架在某些字段上没有针对您的自定义验证逻辑的注释(@NotBlank还不够)。

在这种情况下,您始终可以创建自己的自定义验证器来实现验证逻辑。

是如何执行此操作的示例的链接,但要回顾一下:

  • 您必须实现一个在其方法中实现javax.validation.ConstraintValidator并添加验证逻辑的类public boolean isValid

  • 然后创建一个自定义注解(如@NotBlank but your own one) and set among other things a meta-annotation@Constraint(validatedBy = { YourValidator.class })`

然后像使用任何其他验证注释一样使用此注释


推荐阅读