【问题标题】:Understanding why does sometime "NULL" and sometime "Empty" value is stored to same field?了解为什么有时将“NULL”和有时“空”值存储到同一字段?
【发布时间】:2013-04-10 02:10:05
【问题描述】:

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

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

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

我不明白为什么会这样?谁能解释一下原因?

【问题讨论】:

    标签: validation jakarta-ee web-applications spring-mvc null


    【解决方案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/

    【讨论】:

    • 感谢您的回答!,现在我正在使用 StringUtils 本身。但我需要知道发生这种情况的原因。
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 2017-08-02
    • 1970-01-01
    • 2020-07-17
    • 2020-09-24
    • 1970-01-01
    • 2011-03-19
    • 2014-03-03
    相关资源
    最近更新 更多