此外我们还可以使用注解数据格式化来实现数据类型转换。
例,在vo类的变量声明上添加@DateTimeFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
然后在Spring 的xml文件中配置
<mvc:annotation-driven></mvc:annotation-driven>
可得到与上述设置转换器方法一样的效果。
此外还有@NumberFormat(pattern="#,###,###.")数字格式化。
注意数据类型转换器,与上篇博文中的数据格式化不能同时使用。
若需要同时使用例如:对birth使用数据类型转换器,而对money使用数据格式化。
private Date birth;
@NumberFormat(pattern="#,###,###.")
private int money;
这时我们就会报格式错误的异常,如下。
Field error in object 'userInfo' on field 'mobile': rejected value []; codes [typeMismatch.userInfo.mobile,typeMismatch.mobile,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userInfo.mobile,mobile]; arguments []; default message [mobile]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'mobile'; nested exception is java.lang.NumberFormatException: For input string: ""]
产生这种情况的原因是使用自定义类型转换器时需要通过ConversionServiceFactoryBean的converters属性注册该类型转换器,此时<mvc:annotation-driven/> 默认创建的ConversionService实例不再拥有DefaultFormattingConversionService对象,而是DefaultConversionService对象,无法使用@DateTimeFormat和@NumberFormat注解
这时我们只需要在Spring配置文件中更改 bean 配置的类为FormattingConversionServiceFactoryBean 即可同时使用数据类型转换器和数据格式化。
<bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="dateConverter"/>
</set>
</property>
</bean>
尝试输入
输出