SpringMVC自定义类型转换
方法:使用自定义类型转换器
步骤:
1.第一步:定义一个类,实现 Converter 接口,该接口有两个泛型。
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Mr Z
* @create 2021 01 2021/1/10 13:16
*/
public class StringToDateConverter implements Converter<String, Date> {
//String 接收类型,Date目标类型
/**
*
* @param s 传入字符串的值
* @return
*/
@Override
public Date convert(String s) {
if (s==null){
throw new RuntimeException("无数据");
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return simpleDateFormat.parse(s);
} catch (Exception e) {
throw new RuntimeException("数据类型转换出错");
}
}
}
2.在 spring 配置文件中配置类型转换器。
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!-- 给容器注入一个新的类型转换器 -->
<property name="converters">
<set>
<!-- 类路径-->
<bean class="com.xszx.springmvc.converter.StringToDateConverter"/>
</set>
</property>
</bean>
<!-- 在 annotation-driven 标签中引用配置的类型转换服务-->
<mvc:annotation-driven conversion-service="conversionService"/>