1. 编写类并实现Converter接口(以字符串转日期为例)
package cn.test.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 字符串转日期
*/
public class StirngToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
if(s == null){
throw new RuntimeException("自定义类型转换器:字符串转换日期异常:参数:"+s);
}
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sf.parse(s);
} catch (ParseException e) {
throw new RuntimeException("自定义类型转换器:字符串转换日期异常:参数:"+s);
}
}
}
2. 配置自定义类型转换器(SpirngMVC)并使配置生效
<!--配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.test.utils.StirngToDateConverter"></bean>
</set>
</property>
</bean>
<!--开启springmvc框架注解的支持,生效类型转换器-->
<mvc:annotation-driven conversion-service="conversionService"/>
springmvc.xml