第一步,配置轉換類DateConverter.java
package org.test.base.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
//需要實現Converter接口,這裏是將String類型轉換成Date類型
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
//實現將字符串轉成日期類型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return dateFormat.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果參數綁定失敗返回null
return null;
}
}
第二步,配置spring-mvc.xml,添加代碼
<!--參數綁定string轉Date,start -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<!-- 自定義轉換器的類名 -->
<bean class="org.test.base.converter.DateConverter"></bean>
</property>
</bean>
<!--參數綁定string轉Date,end -->
注注注注注注注注注注: