0

我想將一個LocalDateTime對象以特定格式(yyyy/MM/dd HH:mm)傳遞給thymeleaf,稍後將它接收回我的控制器類。 我想使用customEditor/initbinder來做轉換。Thymeleaf似乎更喜歡使用initString來定義編輯器

/** 
* Custom Initbinder makes LocalDateTime working with javascript 
*/ 
@InitBinder 
public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { 
    binder.registerCustomEditor(LocalDateTime.class, "reservationtime", new LocalDateTimeEditor()); 
} 

public class LocalDateTimeEditor extends PropertyEditorSupport { 

    // Converts a String to a LocalDateTime (when submitting form) 
    @Override 
    public void setAsText(String text) { 
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"); 
     LocalDateTime localDateTime = LocalDateTime.parse(text, formatter); 
     this.setValue(localDateTime); 
    } 

    // Converts a LocalDateTime to a String (when displaying form) 
    @Override 
    public String getAsText() { 
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"); 
     String time = ((LocalDateTime)getValue()).format(formatter); 
     return time; 
    } 

} 

而Spring使用我initbinder當它從形式接收數據,thymeleaf但似乎更喜歡的ToString()方法在我initbinder和我的getAsText()方法不會被調用。

我的觀點:

<input type="text" th:name="${reservationtime}" id="reservationtime" class="form-control" 
             th:value="${reservationtime}"/> 

我找到initbinder 「辦法」 中的代碼可讀性方面相當不錯。所以我想繼續使用initbinder。是否有可能告訴百里香使用我的initbinder或任何其他好的解決方法?

+0

你有沒有嘗試使用雙括號語法('{{ ...}}')?請參閱http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#double-brace-syntax。 – Hidde

+0

我沒有追求initbinder的方法,但你讓我好奇,我試了一下,發現Thymeleaf現在使用它自己的時間格式(dd.MM.yy HH:mm)。它仍然沒有使用我的initbinder。 – ltsstar

回答

0

刪除參數「reservationtime」,可以解決此問題:

binder.registerCustomEditor(LocalDateTime.class, new LocalDateTimeEditor()); 

,然後轉換器將被用於所有LocalDateTime領域