`
leyen
  • 浏览: 4016 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

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/>
分享到:
评论
1 楼 weiqiulai 2013-02-27  
我的环境是spring+mvc 3.0.3.RELEASE,
model中:@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date rectifyDate;// 整改日期
jsp:<input name="rectifyDate" value="<fmt:formatDate value="${dwycl.rectifyDate }" pattern="yyyy-MM-dd"/>" onFocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" class="Wdate" style="width: 80px"/>
修改操作,在点击保存时依然报错:org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'mybean' on field 'rectifyDate': rejected value [2013-02-14]; codes [typeMismatch.mybean.rectifyDate,typeMismatch.rectifyDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [mybean.rectifyDate,rectifyDate]; arguments []; default message [rectifyDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'rectifyDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'rectifyDate': no matching editors or conversion strategy found]
按照你的文章试过了,没有起作用!请楼主指教!!

相关推荐

Global site tag (gtag.js) - Google Analytics