2011-01-26 42 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>