首页 > 解决方案 > 如何在提交操作期间仅在服务端向请求类添加验证

问题描述

我的项目要求仅在提交操作期间向我的请求类添加验证。在保存操作期间,不需要空字段验证。现在我知道了两种验证请求类的方法。

  1. 在相应字段的请求类中使用 @NotBlank 注释。但是我不能使用这种方式,因为我的要求是特定于提交操作的。对于保存和提交,我使用的是相同的请求类。
  2. 使用 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

现在我的问题是,有没有其他更好的方法来实现上述要求。

标签: javaperformancevalidation

解决方案


您可以尝试这种方式来检查 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;            
}

推荐阅读