要解决的问题
springMVC自带了很多自动的数据类型转换器,比如String转Integer,String转Date等,但在String转Date中,2021-01-01无法自动转为Date,所以就需要我们自定义一个数据类型转换类;
步骤
1、写一个String转Date的转换类,该类实现Converter接口,并复写其中的convert方法
package cn.gpxxg.utils.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 类型转换,把String转为Date
*/
public class StringToDate implements Converter<String, Date> {
@Override
public Date convert(String s) {
if (s == null)
throw new RuntimeException("请您传入数据");
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Date parse = null;
try {
parse = date.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return parse;
}
}
2、在springmvc配置文件中配置自定义类型转换器,注入ConversionServiceFactoryBean并加入我们自定义的转换类,并在mvc:annotation-driven中开启自定义类型转换的支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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="cn.gpxxg"></context:component-scan>
<!--加载视图解析器进容器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置跳转地址的前缀-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--配置跳转地址的后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置自定义类型转换器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.gpxxg.utils.converter.StringToDate"></bean>
</set>
</property>
</bean>
<!--springMVC框架开启注解支持-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
</beans>
3、写个页面自测吧