java - 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;
}```
解决方案
如果我理解正确,您会说验证框架在某些字段上没有针对您的自定义验证逻辑的注释(@NotBlank
还不够)。
在这种情况下,您始终可以创建自己的自定义验证器来实现验证逻辑。
这是如何执行此操作的示例的链接,但要回顾一下:
您必须实现一个在其方法中实现
javax.validation.ConstraintValidator
并添加验证逻辑的类public boolean isValid
然后创建一个自定义注解(如
@NotBlank but your own one) and set among other things a meta-annotation
@Constraint(validatedBy = { YourValidator.class })`
然后像使用任何其他验证注释一样使用此注释
推荐阅读
- c# - 如何在 c# 表单中输入 Lshift 和 Rshift?
- ibm-appid - 带有 ADFS 的 IBM APP ID 使用 Windows 集成身份验证 WIA
- android - 使用 Java 将 android studio 连接到 azure sql 数据库
- c# - 长时间运行的计算 .net 核心的性能问题 - 单独的线程池
- java - Java JTabbedPane 只看到一个选项卡
- angular - 改变内容
以编程方式从组件 - html - 为什么div里面的html代码没有被解析?
- android - 在 null 上调用 getter 'length',Flutter 中的错误
- c# - 使用UDP c#发送哈希表
- sql - 用于股票分析的美元加权抽样