java - 如何在提交操作期间仅在服务端向请求类添加验证
问题描述
我的项目要求仅在提交操作期间向我的请求类添加验证。在保存操作期间,不需要空字段验证。现在我知道了两种验证请求类的方法。
- 在相应字段的请求类中使用 @NotBlank 注释。但是我不能使用这种方式,因为我的要求是特定于提交操作的。对于保存和提交,我使用的是相同的请求类。
- 使用 message.properties 文件,我可以在其中定义错误并在我的验证器类中使用它们,例如:
验证器.java
private void validateIncidentDetails(CreateIncidentRequest request) {
...
if(checkForNullOrEmpty(request.getDetectionDate())) {
String msg = messageBundleService.fetchMessage("ERR_EMPTY_DETECTION_DATE");
throw new BadRequestException(msg);
}
---
}
**同样适用于每个领域。
errorMessage.properties
ERR_EMPTY_DETECTION_DATE=Detection Date is required
现在我的问题是,有没有其他更好的方法来实现上述要求。
解决方案
您可以尝试这种方式来检查 null
public boolean checkNull() throws IllegalAccessException {
for (Field f : getClass().getDeclaredFields())
f.setAccessible(true);//to access private property
if (f.get(this) != null)
return false;
return true;
}
推荐阅读
- mongodb - 插入文档时自动包含日期字段
- xml - 如何找出导致“无法解析符号'ActivityMainBindingImpl'”的原因
- python - 如何从测试脚本中运行 WAF 编译的 C++ 程序?
- javascript - 带有字符串格式变量的正则表达式
- pandas - 如何通过检查值是否等于模式来创建二进制熊猫数据框
- python - 此错误的原因是什么,我该如何解决?
- godot - 如何在运行时更改 CollisionShape (3D) 的大小和形状?
- python - Cumsum 重启
- objective-c - 将数据从集合视图传递到表视图
- web - RuntimeError:在请求上下文之外工作。在烧瓶错误