Issue
I have a form field that should be converted to a Date object, as follows:
<form:input path="date" />
But I want to get a null value when this field is empty, instead of that I receive:
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date';
org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type 'java.lang.String' to type 'java.util.Date';
Is there an easy way to indicate that empty Strings should be converted to null? Or should I write my own PropertyEditor?
Thanks!
Solution
Spring provides a PropertyEditor named CustomDateEditor which you can configure to convert an empty String to a null value. You typically have to register it in a @InitBinder
method of your controller:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
// true passed to CustomDateEditor constructor means convert empty String to null
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
Answered By - Chin Huang
Answer Checked By - Cary Denson (JavaFixing Admin)