0

LocalDateTimeオブジェクトを特定のフォーマット(yyyy/MM/dd HH:mm)でthymeleafに渡し、後でそれをコントローラクラスに戻したいとします。 変換を行うためにcustomEditor/initbinderを使用したいと思います。ThymeleafはinitbinderカスタムエディタよりもtoStringを好むようです

/** 
* 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; 
    } 

} 

それは、フォームからのデータを受信したとき、スプリングが私initbinderを使用していますが、thymeleafは、しかし、私のinitbinderと私のgetAsText()メソッドが呼び出されることは決してありません以上の.toString()メソッドを好むようです。

マイビュー:

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

私は、コードの読みやすさの面でinitbinder "道" はかなり良いを見つけます。ですから、私はinitbinderを使い続けたいと思います。 thymeleafに私の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()); 

、その後、コンバータはALLのLocalDateTimeフィールド

関連する問題