問題引出
yyyy/MM/dd格式,轉換成功
yyyy-MM-dd格式,轉換失敗
解決方法
1.編寫自定義轉換器
public class StringToDateConverter implements Converter<String, Date> {
/**
* @param source 輸入框輸入的字符串
* @return
*/
@Override
public Date convert(String source) {
if (source == null) {
throw new RuntimeException("文本框輸入爲空");
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return dateFormat.parse(source);
} catch (ParseException e) {
throw new RuntimeException("無法識別輸入的日期");
}
}
}
2.在配置文件中配置自定義類型轉換器
<!--配置自定義類型轉換器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.sx.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!--配置SpringMVC框架註解支持-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean">
</mvc:annotation-driven>