日期類型轉換器:
在前端頁面的日期文本框中輸入2020/06/26,SpringMVC可以自動對該日期進行轉換,但是當輸入的是2020-06-26時,SpringMVC無法對其自動進行轉換格式,此時就需要我們自定義類型轉換器了。
沒有配置自定義轉換器時運作結果:
接下來就需要進行配置日期轉換器:
//任何自定義轉換器都必須實作Converter接口,該接口有兩個泛型,S:資料源的泛型,T:目标類型的泛型
/**
* @param <S> the source type
* @param <T> the target type
*/
public interface Converter<S, T> {
@Nullable
T convert(S source);
}
/**
* 自定義類型轉換器
*/
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
if(source == null){
throw new RuntimeException("請傳入參數!");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(source);
} catch (Exception e) {
throw new RuntimeException("類型轉換異常");
}
}
}
在springmvc.xml中配置自定義類型轉換器
<!--配置自定義類型轉換器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.itcast.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!--配置springMVC注解掃描支援-->
<mvc:annotation-driven conversion-service="conversionService"/>
運作示範:
運作結果: