Binding Date Form Input On Spring MVC

So you have a form that takes a date input like this:

dateform

It’s always handy to represent the form as a Pojo that gets bound automatically to/from your controller class:

public class AddCustomerForm {
  private String name;
  private String email;
  private Date dob;

  /* getters & setters */
}

Notice the usage of java.util.Date type for the dob field. If you do nothing, the binding wouldn’t work and resulting in error instead because Spring MVC doesn’t know how to convert the text form input into a Date object.

The trick here is to add @DateTimeFormat annotation on the date property:

  @DateTimeFormat(pattern = "dd/MM/yyyy")
  private Date dob;

(Since Spring 3.2 you don’t need Joda library to use this annotation)

Now on your controller the form input will automatically binds into your pojo

public String addCustomer(@ModelAttribute("addCustomerForm") AddCustomerForm form) {
  // do something with form input ..
}
About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

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