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

字符串转换日期:

1.自定义一个类

 1 /**
 2  * 字符串转换日期
 3  */
 4 public class StringToDateConverter implements Converter {
 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     class="org.springframework.context.support.ConversionServiceFactoryBean">
 3         
 4             
 5                 class="cn.flypig666.utils.StringToDateConverter">
 6             
 7         
 8     
 9 
10     
11     

 

你可能感兴趣的:(springmvc:自定义类型转换器代码编写)