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

Advertisements

7 thoughts on “Binding date in Spring!”

  1. Somebody necessarily help to make critically articles I’d state.
    That is the first time I frequented your web page and
    to this point? I surprised with the analysis you made to create this actual publish incredible.
    Wonderful process!

    Like

  2. Hi Ankeet, I have some issue with initBinder.My search page have 4 search criteria.1 search criteria as Date.So I’m getting defaul dates from java script.So When I want to search with other 3 search criteria and removing date.So it’s not loading page.Could you please give me solution.
    My InitBinder is below
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    binder.setDisallowedFields(new String[] {“shpm_num”,”part_num”,”origin”,”destination”,”bpo”});
    binder.setRequiredFields(new String[] {“date_from”,”date_to”});
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    Like

    1. @InitBinder goes into your Controller class to change the date format which is coming from your JSP.

      I’m afraid I’m not sure of what you mean when you say the page is not loading.

      And if you want to search with other 3 fields and not with date, you would be making the user to click a button or link, on click of that you can see if the Date field is empty, if it is send a hidden parameter whose presence you can check in the controller, and if it’s absent you can have the three fields and can do your business logic.

      @InitBinder is just to change the binding of data, whatever format you specify it will convert it to that. Maybe check the format of your date which gets populated by the Javascript Calender, if you’re using one.

      You only need to use @InitBinder for the fields which you want to convert, not for other ones, they will be untouched by the Spring Container.

      One of the reasons which might cause not population of your date is the Model Attribute (form backing object). Check if it’s containing the date or not.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s