解决方案:提供专门的类型转换器
定义转换器类
package com.haitai.oa.component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* 实现从前台传入的时间字符串自动转为Date对象
*
* @author root
*
*/
public class CostomDateConvert implements Converter<String, Date> {
@Override
public Date convert(String source) {
if (source == null || source.isEmpty()) {
return null;
}
// 定义支持的时间字符串格式
SimpleDateFormat[] simpleDateFormats = new SimpleDateFormat[] { new SimpleDateFormat("yyyy-MM-dd HH:mm") };
for (SimpleDateFormat simpleDateFormat : simpleDateFormats) {
try {
return simpleDateFormat.parse(source);
} catch (ParseException e) {
continue;
}
}
return null;
}
}
接下来就是对spring-mvc.xml(注:配置文件名可不同,本示例配置的该文件)进行配置,使其生效
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<mvc:default-servlet-handler />
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<mvc:annotation-driven conversion-service="convertorService"></mvc:annotation-driven>
<!-- 设置自定义的转换器 -->
<bean id="convertorService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.haitai.oa.component.CostomDateConvert"></bean>
</list>
</property>
</bean>
</beans>
注:设置自定义的转换器 配置代码中,
<bean class="com.haitai.oa.component.CostomDateConvert"></bean> 红色部分,需要根据自己实际情况填写
另外需要注意的地方,如下图红框标示
红框标示的两处地方必须一致,至此,重启项目后转换器就会默默工作了