So you have a form that takes a date input like this:
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 annotation on the date property:
(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(("addCustomerForm") AddCustomerForm form) { // do something with form input .. }
hi Jerry, I like your post, you seem to be an expert that could help me with the following problem:
I keep getting this error on binding a Date field:
Field error in object ‘filter’ on field ‘expiredDateFrom': rejected value [12.04.2014 11:20]; codes [typeMismatch.filter.expiredDateFrom,typeMismatch.expiredDateFrom,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [filter.expiredDateFrom,expiredDateFrom]; arguments []; default message [expiredDateFrom]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Date’ for property ‘expiredDateFrom'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property ‘expiredDateFrom': no matching editors or conversion strategy found]
It seems the formatting annotations on my bean are completely ignored, I tried several datetime formats, nothing ever worked.
My setting is:
mvc portlet in Liferay, spring framework 4.0.2 release, Tomcat.
I have the required spring configuration entries including:
–
–
and I have joda library in classpath (through pom file)
The Date field annotation for the field with the above error: (pattern=”dd.MM.yyyy HH:mm”)
Do you have any idea what else I should check?
Hmm sorry I can’t see what’s wrong either, you seem to have all the components correct. I recommend you create a small project where the error can be reproduced and upload it to github so I can test it. Also include the instruction on how to run the code.
Hey thanks! your post really helped me with the Date problem I had for Spring MVC.