spring mvc3.1.0 日期自动转换

最近在学习spring mvc,版本是3.1.0,在测试类型自动转换的时候,对日期类型转换总是抛异常,通过度娘的帮助也没有解决这个问题,大多是教你怎么写自定义日期转换,并注入到controller中的,不是我想要的,后来查spring reference终于搞定.
在spring reference中第16.14节(16.14 Configuring Spring MVC)中有关于MVC的配置介绍,
其中有句话
3. Support for formatting Date, Calendar, Long, and Joda Time fields using the @DateTimeFormat
annotation, if Joda Time 1.3 or higher is present on the classpath.

看到这句话之后发现我的classpath中确实没有这个joda time jar包,去网站下来一个扔到classpath里,解决了问题.

心得:不读书不看报真是不行!

以下是我对spring mvc自动对String ->java.util.Date 转换的整理记录,希望对和我一样的spring mvc小白有所帮助.

spring mvc3 支持将表单内容自动转换成POJO,对于POJO中的java.util.DateL类型的自动转换需要注意如下几点:
1:需要在classpath中有 joda-time-1.3(+).jar
2:POJO的Date类型属性上需要加 @DateTimeFormat,格式可以是下边这样:
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd")
在一个表单中可同时支持这3种类型
3:在mvc的配置文件中需要加 <mvc:annotation-driven/>

猜你喜欢

转载自leyen.iteye.com/blog/1740804