Tag Archives: date binding in spring

Binding date in Spring!

Almost often, we have a situation that a Date field is a part of our domain object. And we rely on Spring for binding this domain object with the view so as to minimize the hassles of dealing with the fields individually, and then setting them in the object in controller.

Let’s suppose we have a domain entity, Book, which has some customary fields (along with the dreaded field Date too) shown in the form below.

So lets now try our luck filling this form. So, there we go.

But, binding date isn’t that straightforward. If you ever tried to bind the date, you must have inevitably got the following error message:

Failed to convert property value of type java.lang.String to required type java.util.Date for property date; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property date: no matching editors or conversion strategy found

And even if you by passed the bean validation, your Controller would return a null for the corresponding date field.

Well, there are two easy solutions.

First: Very Easy Solution

This doesn’t asks you to do anything in your code, but limits your input to a date, whose separators should only and only be ‘/’. E.g. dd/MM/yyyy , yyyy/MM/dd, yyyy/MMM/dd

So, now filling the above information by using “/” as separators and submitting the page.

So this was the first solution.

Second: Easy Solution (Using InitBinder)

This method gives you the freedom, to get your date input in whichever format you like, and with whatsoever separators you desire.

All you need to do is to place this code-snippet in your Controller.


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

With this you specify to the Container that you’ll be inputting the date in this very format, and he will do the rest for you.

Let’s try a very bizarre format, dd==MMM==yyyy

To accommodate this above format, change the format declared in InitBinder,


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

Filling in the form with our new date format.

Lets see if it passes the litmus test on submitting the page.

Bingo it did! And all we did was to change the format in Controller, so you can set any format and be assured, you won’t get any ugly surprises(exceptions!).

Download Source Code

You can download the source code from here