【问题标题】:Spring Web Flow blank binding should be null, not empty StringSpring Web Flow 空白绑定应该为空,而不是空字符串
【发布时间】:2016-08-08 03:47:57
【问题描述】:

给定以下视图状态和绑定:

<view-state id="updatePartner" view="/partners/partnerForm" model="partner">
    <binder>
        <binding property="name" required="true" />
        <binding property="address" required="true" />
        <binding property="address2" />
        <binding property="city" required="true" />
        <binding property="state" required="true" />
        <binding property="zip" required="true" />
        <binding property="phone" required="true" />
    </binder>
    ...
</view-state>

我在地址 2 中获得了一个带有“”的合作伙伴对象。我想要一个空值。

如何强制使用 null 而不是空白字符串?我想避免将空白字符串强制转换为 nulls 的显式 POJO 设置器。

我查看了转换器,但那些似乎从一种类型转换为另一种类型(即字符串到长等),我认为如果我创建一个转换器来将所有字符串转换为字符串,它会为应用程序创建额外的工作并使其删除空白字符串,此外,理论上这可能会破坏其他我不想碰的东西。

我看到了 StringTrimmerEditor 选项 (https://stackoverflow.com/a/2977863/3810920),我可以看到 InitBinder 方法被调用,但我的 POJO 在地址 2 中仍然有“”。

谢谢!

【问题讨论】:

    标签: java spring thymeleaf spring-webflow


    【解决方案1】:

    您可以创建自定义转换器:

    public class EmptyStringToNullConverter extends StringToObject {
    
        public EmptyStringToNullConverter() {
            super(String.class);
        }
    
        @Override
        protected Object toObject(String string, Class targetClass) throws Exception {
            return StringUtils.isNotBlank(string) ? string : null;
        }
    
        @Override
        protected String toString(Object object) throws Exception {
            return object.toString();
        }
    }
    

    然后添加您的 ApplicationConversionService

    addConverter("emptyToNullString", new EmptyStringToNullConverter());
    

    那么你可以使用:

    <binding property="name" converter="emptyToNullString"/>
    

    【讨论】:

    • 听起来不错!我仍然希望有一个我可以利用的现有转换器,即使您的转换器非常优雅!
    • 我仍在尝试自己弄清楚。必须明确使用转换器很烦人
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2013-05-13
    相关资源
    最近更新 更多