0

LocalDateTime オブジェクトを特定の形式 (yyyy/MM/dd HH:mm) で thymeleaf に渡し、後でそれをコントローラー クラスに戻したいと考えています。customEditor / initbinder を使用して変換を行いたいです。

/**
 * 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 は initbinder よりも .toString() メソッドを好むようで、getAsText() メソッドが呼び出されることはありません。

私の見解:

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

コードの読みやすさという点では、initbinder の「方法」は非常に優れていると思います。だから私はinitbinderを使い続けたいと思います。thymeleaf に initbinder またはその他の適切な回避策を使用するように指示することは可能ですか?

4

1 に答える 1

0

パラメータ「reservationtime」を削除すると、問題が解決する場合があります。

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

そして、コンバーターはすべての LocalDateTime フィールドに使用されます

于 2017-12-02T10:47:21.773 に答える