参考:Spring Framework 中文文档 - 22. Web MVC 框架 | Docs4dev
(9条消息) SpringMVC--Converter(类型转换器)详解_吴声子夜歌的博客-CSDN博客
案例:
package com.test.convert;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
//String source要进行转换的字符串
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(source);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("String转Date转换异常");
}
}
}
在xml中配置
<!--加载mvc注解驱动-->
<!--注册类型转换服务conversion-service="conversionService"-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--配置类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!--给工厂注入一个新的类型转换器-->
<property name="converters">
<array>
<!--配置自定义转换器-->
<bean id="dateConverter" class="com.zhang.convert.DateConverter"></bean>
</array>
</property>
</bean>