springmvc类型转换器
package com.orange.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.springframework.core.convert.converter.Converter;
public class MyDateConverter implements Converter<String, Date> {
public Date convert(String source) {
try {
SimpleDateFormat sdf = getSimpleDateFormat(source);
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
private SimpleDateFormat getSimpleDateFormat(String source){
SimpleDateFormat sdf = null;
if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)){
sdf = new SimpleDateFormat("yyyy-MM-dd");
}else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)){
sdf = new SimpleDateFormat("yyyyMMdd");
}else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)){
sdf = new SimpleDateFormat("yyyy/MM/dd");
}
return sdf;
}
}
注册类型转换器,配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="com.orange.controller" />
<!-- 开启类型转换服务 -->
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 注册自定义类型转换器 -->
<bean id="dateConverter" class="com.orange.converter.MyDateConverter"></bean>
<!-- 注册类型转换服务 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters" ref="dateConverter"></property>
</bean>
</beans>

浙公网安备 33010602011771号