使用Spring将空String转换为null Date对象

Joa*_*les 30 java spring spring-mvc

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

<form:input path="date" />
Run Code Online (Sandbox Code Playgroud)

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

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';
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来指示空字符串应该转换为null?或者我应该写自己的PropertyEditor

谢谢!

Chi*_*ang 48

Spring提供了一个名为CustomDateEditor的PropertyEditor ,您可以将其配置为将空String转换为空值.您通常必须在@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));
}
Run Code Online (Sandbox Code Playgroud)


Giu*_*lli 6

更新版本的Spring框架引入了转换和格式化服务来处理这些任务,以某种方式使属性编辑器系统落后.但是,遗憾的是,仍然存在报告的问题:默认情况下DateFormatter 无法将空字符串正确转换null Date对象.我觉得非常恼火的是,Spring文档包含一个日期格式化代码片段示例,其中为两个转换(往返字符串)实现了适当的保护子句.框架实现和框架文档之间的这种差异确实让我感到疯狂,甚至在我找到一些时间投入到任务时我甚至可以尝试提交补丁.

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

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

要提供特定的日期格式,必须正确设置bean 的pattern属性DateFormatter.

<beans:bean class="com.example.util.DateFormatter">
    <beans:property name="pattern" value="yyyy-MM-dd" />
</beans:bean>
Run Code Online (Sandbox Code Playgroud)