您的位置:首页 > 其它

自定义数据类型转换器的开发步骤

2017-11-10 09:23 363 查看
自定义数据类型转换器的开发步骤:

  1.编写一个类,实现converter接口

      
public class CustomDateConverter implements Converter<String,Date>{

@Override
public Date convert(String source) {
//使用自定义时间转换器,完成多种时间格式转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.parse(source);
} catch (ParseException e) {
//e.printStackTrace();
sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(source);
} catch (ParseException e1) {
sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
return sdf.parse(source);
} catch (ParseException e3) {
sdf = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
try {
return sdf.parse(source);
} catch (ParseException e4) {
}
}
}
}
return new Date();//如果时间格式都不满足,则返回当前系统时间
}

}
      

  2.配置一个转换工厂,使用自定义的转换器

    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="com.neuedu.mvcdemo.view.converter.CustomDateConverter"/>
</list>
</property>
</bean>

 3.使用定义的转换工厂

   <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 4.文档头部定义:  

      <beans default-lazy-init="false"
xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: