【发布时间】:2014-03-06 17:35:12
【问题描述】:
我有一个模型类
class SomeClass {
private DateTime myDate;
// setter & getter
}
和一个控制器:
@Controller
class MyController {
@RequestMapping("...")
public String doStuff(@ModelAttribute("myAttribute") SomeClass value) {
// ...
}
}
当使用适当的<input type="datetime" .../> 字段从 HTML5 表单调用此控制器时,我收到以下错误:
字段“myDate”上的对象“myAttribute”中的字段错误: 拒绝值 [2014-02-08T23:00:00.00Z];代码 [typeMismatch.myAttribute.myDate,typeMismatch.myDate,typeMismatch.org.joda.time.DateTime,typeMismatch]; 论据 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [myAttribute.myDate,myDate];论据 []; 默认消息 [myDate]];默认消息[转换失败 “java.lang.String”类型的属性值到所需类型 属性“myDate”的“org.joda.time.DateTime”;嵌套的 异常是 java.lang.IllegalStateException:无法转换的值 类型 [java.lang.String] 到所需类型 [org.joda.time.DateTime] 属性“myDate”:没有匹配的编辑器或转换策略 找到]
这让我很困惑,因为据我了解7.6.5 Configuring Formatting in Spring MVC 在manual:
如果还安装了对 Joda Time 格式库的完全支持 Joda Time 存在于类路径中。
转换应该开箱即用(我使用的是 spring 4.0 和 Joda time 2.3)。即使格式可能错误,至少它应该找到一个转换器。但是我认为应该尝试按照7.7 Configuring a global date & time format 部分中的说明配置日期格式。在谷歌关于 HTML5 日期字段格式和 Javadoc 的一些额外帮助下,我想出了这个:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatterRegistrars">
<set>
<bean class="org.springframework.format.datetime.joda.JodaTimeFormatterRegistrar">
<property name="useIsoFormat" value="true" />
</bean>
</set>
</property>
</bean>
但是,我刚刚插入到 applicationContext.xml 中的那些行的效果根本没有效果。
那么我需要做些什么才能正确设置(另外我想避免在我的模型对象上使用@DateTimeFormat 注释,因为我的模型对 HTML 一无所知,所以我觉得附加有关该对象的 HTML5 格式的信息)。
【问题讨论】:
标签: java spring-mvc jodatime