在使用SpringMVC从前台获取用户数据然后存入库中时,有时候会出现类型错误,比如输入日期为:
2020-04-22,提交时就会报输入异常,所有我们就要考虑自定义类型转换器了!
1.首先得实现Converter接口
注意Converter接口在:org.springframework.core.convert.converter.Converter包下
public class StringToDateConverter implements Converter<String, Date> {
/**
* source 传入的字符串
* @param source
* @return
*/
@Override
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("数据类型转换出现错误");
}
}
}
2.然后在ConversionServiceFactoryBean中注入我们定义的转换器(web.xml文件中)
<!-- 配置自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.itt.utils.StringToDateConverter"/>
</set>
</property>
</bean>
3.最后开启SpringMVC对于类型转换的支持
<mvc:annotation-driven conversion-service="conversionService"/>