Let say i have this java bean,
public class MyBean implements Serializable {
private Integer id;
private String userid;
private Date contacttime;
// other setter and getter
And i have a SpringMVC Controller like this, using @ModelAttribute as the method’s parameter,
@RequestMapping(value = "/doSomething", method = RequestMethod.POST)
public @ResponseBody Object doSomething(@ModelAttribute MyBean myBean) {
// do something
}
Im sending HTTP Post which format is like this
id=2&
userid=3abc&
contacttime=130314101010
But it shows error on my server side, which looks like this,
Failed to convert from type java.lang.String to type java.util.Date for value '130314101010';
nested exception is java.lang.IllegalArgumentException
Usually, i have to manually use SimpleDateFormat to parse my “ddMMyyHHmmss” String into Date, but SpringMVC provide a very elegant way of handling with this kind of conversion. Just by using @DateTimeFormat
import org.springframework.format.annotation.DateTimeFormat;
public class MyBean implements Serializable {
private Integer id;
private String userid;
@DateTimeFormat(pattern = "ddMMyyHHmmss")
private Date contacttime;
// other setter and getter
Dont forget to include JodaTime on your pom.xml
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
If not, you will find this kind of error,
org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Date for value '130314101010'; nested exception is java.lang.IllegalStateException: JodaTime library not available - @DateTimeFormat not supported
Have fun with SpringMVC 😀