第一步:定义一个类,实现 Converter 接口,该接口有两个泛型。

public class StringToDateConverter implements Converter<String, Date> {
/**
* 用于把 String 类型转成日期类型
*/
@Override
public Date convert(String source) {
DateFormat format = null;
try {
if(StringUtils.isEmpty(source)) {
throw new NullPointerException("请输入要转换的日期");
}
format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(source);
return date;
} catch (Exception e) {
throw new RuntimeException("输入日期有误");
}
}
}

第二步:在 spring 配置文件中配置类型转换器

spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去。

<!-- 配置类型转换器工厂 -->
<bean id="converterService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 给工厂注入一个新的类型转换器 -->
<property name="converters">
<array>
<!-- 配置自定义类型转换器 -->
<bean class="com.itheima.web.converter.StringToDateConverter"></bean>
</array>
</property>
</bean>

第三步:在 annotation-driven 标签中引用配置的类型转换服务

<!-- 引用自定义类型转换器 -->
<mvc:annotation-driven
conversion-service="converterService"></mvc:annotation-driven>