Thursday, April 4, 2013

Spring MVC - Bind an input field to a Date property

For request parameters representing string, number, and boolean values, the Spring MVC container can bind them to typed properties out of the box. Suppose you have the Date Input field, and the bean property is defined as Date Type, when container tries to bind it will throw exception

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date'

So we need to create a binding between your input field and your bean's Date property. Spring provides a PropertyEditor named CustomDateEditor which you can configure to convert an String to respective date format. You typically have to register it in a @InitBinder method of your controller

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

Happy Programming..!!!

No comments:

Post a Comment