问题
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