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.xmljava
<?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>