1. 摘要
本文主要讲解Spring mvc数据格式化的具体步骤;
并讲解前台日期格式如何转换为java对象;
在之前的文章《
【Spring学习笔记-MVC-8】SpringMVC之类型转换Converter
》(对应链接:
http://www.cnblogs.com/ssslinppp/p/4598102.html )
中讲解了Spring MVC的
类型转换
,在此回顾下。
数据格式化,从本质上讲属于数据转换的范畴。Spring就是基于数据转换框架植入“格式化”功能的。
在数据转换时我们进行了如下配置:
![](https://i-blog.csdnimg.cn/blog_migrate/f914424f66876eb408fcfb9254bf5723.png)
我们使用的是ConversionServiceFactoryBean,而进行数据格式化时,只是将ConversionServiceFactoryBean改为FormattingConversionServiceFactoryBean即可,其他没有变化,如下是数据格式化的配置:
![](https://i-blog.csdnimg.cn/blog_migrate/ecf1da3ffdfecd55a1fe2d6e2e219262.png)
关于
FormattingConversionServiceFactoryBean与
ConversionServiceFactoryBean的比较:
- ConversionService:只有数据转换功能;
- ConversionServiceFactoryBean:与ConversionService对应;
- FormattingConversionService:具有数据转换和数据格式化功能;
- FormattingConversionServiceFactoryBean:与FormattingConversionService对应;可以注册自定义的转换器,又可以注册自定义的注解驱动器逻辑。
<mvc:annotation-driven/>标签内部默认创建的conversionService实例就是一个FormattingConversionServiceFactoryBean;
装配完FormattingConversionServiceFactoryBean后,Spring MVC对处理方法的入参绑定就支持注解驱动的功能了。
2. 具体实现
步骤1:配置FormattingConversionServiceFactoryBean
![](https://i-blog.csdnimg.cn/blog_migrate/bbe67cc47148342e8333559c9134e242.png)
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- <bean class="com.ll.model.StringToPersonConverter" /> -->
</list>
</property>
</bean>
步骤2:使用@DateTimeFormat和@NumberFormat注解对象属性
![](https://i-blog.csdnimg.cn/blog_migrate/0bec5a0dca9782ad473eafe4147f4f2d.png)
步骤3:控制层
![](https://i-blog.csdnimg.cn/blog_migrate/6649f906446bc204ef6b9dd6f8a63ce7.png)
步骤4:前台请求
![](https://i-blog.csdnimg.cn/blog_migrate/5c484e5a1f5f4d9116b6f1cf89ee5780.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f139071df05208b592d3927162bde237.png)
![](https://i-blog.csdnimg.cn/blog_migrate/49e7f4af175096bd74053a6937f47cb9.png)
3. 简单介绍@DateTimeFormat与@NumberFormat
![](https://i-blog.csdnimg.cn/blog_migrate/ce837296946a5924dc8250179a20f4a0.png)
![](https://i-blog.csdnimg.cn/blog_migrate/deb7790aeee1e07bbcbfeb8ef87c12d7.png)
附件列表
转载请标明出处:http://www.cnblogs.com/ssslinppp/