SpringMvc中将请求数据中的字符串转换成Date日期格式的数据

1.定义一个类实现Converter接口,并且实现该接口的方法

//利用泛型将字符串类型转为日期类型,第一个参数:表示要转换的字符串 ,第二个参数:要转换到的类型
public class CostomDateConvert implements Converter<String, Date>{

    @Override
    public Date convert(String info) {
        // TODO Auto-generated method stub
        if (info == null || info.isEmpty()) {
            return null;
        }
//      定义一个数组保存支持的格式
        SimpleDateFormat[] simpleDateFormats = new SimpleDateFormat[] {
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
            new SimpleDateFormat("yyyy/MM/dd"),
        };
        for (SimpleDateFormat simpleDateFormat : simpleDateFormats) {
            try {
                return simpleDateFormat.parse(info);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                continue;
            }
        }
        return null;
    }
}

2.在spring-mvc.xml中设置转换器

<!-- 设置自定义的转换器 -->
         <bean id="convertorService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <bean class="com.qianfeng.trans.CostomDateConvert"></bean>
                    <bean class="com.qianfeng.trans.CustomIntConvert"></bean>
                </list>
            </property>
         </bean>

3.并且在spring-mvc.xml中的mvc:annotation-driven中指定上面设置的转换器

<!--conversion-service:指定需要用到的日期转换器  -->
        <mvc:annotation-driven conversion-service="convertorService"></mvc:annotation-driven>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,126评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 23,075评论 1 92
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,346评论 6 342
  • 填词:花槿 原曲:双笙-《镜花水月》 原词作:苍苍 原曲作:砖厂浪人 To:媳妇~~~ —————————————...
    一戏清平阅读 234评论 0 0
  • 1.懒人做饭也可以做得很健康,中午的午餐是千年谷种红米浆➕一锅蒸红薯,公公最喜欢吃红薯了。其实我也蛮喜欢吃的,当然...
    雪纷阅读 325评论 2 7

友情链接更多精彩内容