创建一个转换类
要继承一个Converter类,才能定义
代码语言:javascript复制import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
配置到spring-mvc.xml中
代码语言:javascript复制 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描包-->
<context:component-scan base-package="com.itheima.controller"/>
<!-- 声明是为了对springmvc的组件做增强-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
<!-- 配置自定义的类型转换器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.itheima.converter.StringToDateConverter"/>
</set>
</property>
</bean>
</beans>
注解方式
只需在要再要转换的类型上加上一个 @DateTimeFormat(pattern = “yyyy-MM-dd”) 如下:
代码语言:javascript复制 @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date ser;