2

目前我正在开发 spring(MVC) web 应用程序,在验证控制器中的实体类字段时发现了一些奇怪的东西。每当我在每次提交表单后尝试进行验证时,我都会对存储在实体类字段中的值感到困惑。

例如,以下是我用于验证字符串字段之一的代码片段。它工作正常,但有时不行。我发现的原因是有时Null value设置,有时Empty value设置为same field.

if(entity.getWhoBookedIt().equals("")){
  bindingResult.rejectValue("whoBookedIt", "NotEmpty.java.lang.String", null, null);
}

我不明白为什么会发生这种情况?有人可以解释一下原因吗?

4

1 回答 1

1

我知道这并不能真正回答您的问题,但作为一种解决方案,您可以使用 Apache 的 StringUtils 类来检查两者。

if(StringUtils.isEmpty(entity.getWhoBookedIt()){
    bindingResult.rejectValue("whoBookedIt", "NotEmpty.java.lang.String", null, null);
}

从 StringUtils 类:

public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
}

http://commons.apache.org/proper/commons-lang/

于 2013-04-17T15:12:56.330 回答