自定义类型转换器
mvc框架自动进行数据类型转换
在User类中我们新增加了一个用户生日的属性,Date类型。
当我们前端传入格式是xxx/xx/xx这样的格式才成功提交到后台,如果是其他形式就会bad request,怎么自定义类型转换器呢。
第一步
定义一个类,实现converter接口,该接口有两个泛型
编写一个类继承converter接口
package cn.itcast.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Classname StringToDateConverter
* @Description 字符串转换成日期
* @Date 2020/1/20 15:07
* @Created by mmz
*/
public class StringToDateConverter implements Converter<String,Date> {
@Override
public Date convert(String source) {
//判断
if(source == null){
throw new RuntimeException("请您传入参数");
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//把字符串转换成日期
try {
return dateFormat.parse(source);
} catch (ParseException e) {
throw new RuntimeException("数据类型转换出现异常");
}
}
}
再在springmvc配置中配置这个bean
<!--配置自定义转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>