springmvc:自定义类型转换器代码编写

字符串转换日期:

1.自定义一个类

 1 /**
 2  * 字符串转换日期
 3  */
 4 public class StringToDateConverter implements Converter<String, Date> {
 5 
 6     /**
 7      * String source    传入进来字符串
 8      * @param source
 9      * @return
10      */
11     @Override
12     public Date convert(String source) {
13         //判断
14         if(source == null){
15             //抛出运行时异常
16             throw new RuntimeException("请您传入数据");
17         }
18         DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
19         try {
20             //把字符串转换日期
21             return df.parse(source);
22         } catch (ParseException e) {
23             throw new RuntimeException("数据类型转换出现错误");
24         }
25 
26     }
27 }

二、在springmvc.xml中配置自定义类型转换器

 1     <!--配置自定义类型转换器-->
 2     <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
 3         <property name="converters">
 4             <set>
 5                 <bean class="cn.flypig666.utils.StringToDateConverter"></bean>
 6             </set>
 7         </property>
 8     </bean>
 9 
10     <!--开启SpringMVC框架注解的支持-->
11     <mvc:annotation-driven conversion-service="conversionService"/>

猜你喜欢

转载自www.cnblogs.com/flypig666/p/11517536.html
今日推荐