使用 Spring 将空字符串转换为空 Date 对象

2022-09-01 10:35:20

我有一个表单字段,应该转换为日期对象,如下所示:

<form:input path="date" />

但是我想在这个字段为空时得到一个空值,而不是我收到的:

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date';
org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type 'java.lang.String' to type 'java.util.Date';

有没有一种简单的方法来指示空字符串应转换为 null?还是我应该写我自己的财产编辑器

谢谢!


答案 1

Spring提供了一个名为CustomDateEditor的属性编辑器,您可以将其配置为将空字符串转换为空值。通常必须在控制器的方法中注册它:@InitBinder

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);

    // true passed to CustomDateEditor constructor means convert empty String to null
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

答案 2

Spring框架的最新版本引入了转换和格式化服务来处理这些任务,以某种方式将属性编辑器系统抛在后面。但是,不幸的是,报告的问题仍然存在:默认值无法将空字符串正确转换为对象。我发现非常恼火的是,Spring文档包含一个日期格式化程序片段示例,其中为两个转换(到字符串和从字符串)实现正确的保护子句。框架实现和框架文档之间的这种差异确实让我发疯,以至于我甚至可以在找到一些时间投入到任务中时立即提交补丁。DateFormatternullDate

同时,我对在使用Spring框架的现代版本时遇到此问题的每个人的建议是,对默认值进行子类化并覆盖其方法(如果需要,它的方法也是如此),以便以文档中所示的方式添加一个保护子句。DateFormatterparseprint

package com.example.util;

import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

public class DateFormatter extends org.springframework.format.datetime.DateFormatter {

    @Override
    public Date parse(String text, Locale locale) throws ParseException {
        if (text != null && text.isEmpty()) {
            return null;
        }
        return super.parse(text, locale);
    }

}

然后,必须对 XML Spring 配置进行一些修改:必须定义转换服务 Bean,并且必须正确设置命名空间中元素中的相应属性。annotation-drivenmvc

<mvc:annotation-driven conversion-service="conversionService" />
<beans:bean
    id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <beans:property name="formatters">
        <beans:set>
            <beans:bean class="com.example.util.DateFormatter" />
        </beans:set>
    </beans:property>
</beans:bean>

要提供特定的日期格式,必须正确设置 Bean 的属性。patternDateFormatter

<beans:bean class="com.example.util.DateFormatter">
    <beans:property name="pattern" value="yyyy-MM-dd" />
</beans:bean>

推荐