Spring MVC中自定义类型转发器

代码如下:

package com.lzw.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 把字符串转换日期
*/
public class StringToDateConverter implements Converter<String,Date>{

/**
* String source 传入进来字符串
* @param source
* @return
*/
public Date convert(String source) {
// 判断
if(source == null){
throw new RuntimeException("请您传入数据");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

try {
// 把字符串转换日期
return df.parse(source);
} catch (Exception e) {
throw new RuntimeException("数据类型转换出现错误");
}
}

}

这里实现自定义类转换只需实现Converter接口即可


配置文件中的配置:

<!--配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
                <set>
                         <bean class="cn.itcast.utils.StringToDateConverter"/>
                </set>
        </property>
</bean>

 

posted @ 2019-09-11 22:24  文所未闻  阅读(254)  评论(0编辑  收藏  举报