2011-01-26 76 views
30

我有一个表格字段应转换为Date对象,如下所示:转换为空字符串为空Date对象与Spring

<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'; 

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

谢谢!

+0

如果你没有注册一个自定义的PropertyEditor,它对于非空字符串如何工作? – axtavt 2011-01-26 16:15:05

+0

由于Spring有一些内置的PropertyEditors,如下所示:http://static.springsource.org/spring/docs/3.0.3.RELEASE/spring-framework-reference/html/validation.html#beans-beans-转换 – 2011-01-27 12:47:11

回答

48

Spring提供了一个名为CustomDateEditor的PropertyEditor,您可以将其配置为将空字符串转换为空值。你通常在你的控制器的@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)); 
} 
5

更多的Spring框架引入了转换和格式化服务的最新版本,以充分利用这些任务的照顾,不知何故离开属性编辑器系统之后。但是,报告的问题不幸仍然存在:默认的DateFormatteris unable to properly convert空字符串到nullDate对象。我发现非常恼人的是Spring文档contains a date formatter snippet example where the proper guard clauses are implemented这两个转换(来自和来自字符串)。框架实现和框架文档之间的这种差异确实使我非常疯狂,以至于我一有时间就会致力于完成任务,甚至可以尝试提交补丁。

在此期间,我建议大家在使用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); 
    } 

} 

然后,一些修改必须被施加到XML Spring配置:转换服务豆必须被定义,并且在mvc命名空间中的annotation-driven元件相应的属性必须正确设置。

<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> 

要提供具体的日期格式,该DateFormatter bean的pattern属性必须正确设置。

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