簡體   English   中英

使用 Spring 將空字符串轉換為空日期對象

[英]Converting empty String to null Date object with Spring

我有一個應轉換為 Date 對象的表單字段,如下所示:

<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? 或者我應該編寫自己的PropertyEditor嗎?

謝謝!

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

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

}

然后,必須對 XML Spring 配置進行一些修改:必須定義一個轉換服務 bean,並且必須正確設置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>

使用 Spring 5,這個錯誤仍然可能會非常錯誤地發生.... ....如果你有一個映射集合,例如這樣,請確保你的索引在集合中是正確的(這來自 Spring Controller 中的 @initBinder)

if(sm != null && sm.getSapSaleItems() != null) {
        int i = sm.getSapSaleItems().size();
        for (int x = 0; x < i ; x++) {
            binder.registerCustomEditor(Date.class, "salesOrderItems[" + i + "].pickDate",
                    new CustomDateEditor(dateFormatter, true));
            
        }

"i" 應該是 x ))),創建相同的錯誤,即空字符串不能轉換為日期:

默認消息 [salesOrderItems[1].pickDate]]; 默認消息 [無法將類型為 'java.lang.String' 的屬性值轉換為屬性 'salesOrderItems[1].pickDate' 所需的類型 'java.util.Date'; 嵌套異常是 org.springframework.core.convert.ConversionFailedException:無法從類型 [java.lang.String] 轉換為值 '' 的類型 [java.util.Date]; 嵌套異常是 java.lang.IllegalArgumentException]

jsp 代碼應該是這樣的:

<td><form:input cssClass="datepicker" size="10"
                                    path="salesOrderItems[${loopStatus.index}].pickDate" /></td>

...另一個原因,同樣的配置,你可能會得到同樣的誤導性錯誤,如果 sap 線的嵌套集合(見我的例子)在表單支持對象中不可用......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM