Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for prope

半城伤御伤魂 提交于 2019-12-12 04:37:21

问题


I am building a web application using Thymeleaf and SpringBoot, I am new to both the technologies.

In my html file, there is a Date field as follows:

<input type="date" th:field="*{issueDate}" />

My model class has a field corresponding to issueDate as follows:

@NotNull(message = "Cannot be empty")
private Date issueDate;

When I input a date from the UI, I see the following exception in the browser:

    Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property issueDate;

From my experience, I understand that the UI reads the property as a String, but the model expects a type Date due to which the error occurs. So I need to convert the String to a Date. However where should this be done? Since the error occurs even before the setter method in the model is invoked.

Any help would be much appreciated! Thanks in advance!


回答1:


In your controller:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}

WHERE "MM/dd/yyyy" is the date format you're using.



来源:https://stackoverflow.com/questions/41009394/thymeleaf-and-springboot-failed-to-convert-property-value-of-type-java-lang-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!