springMVC自定義型別轉換器(date型別轉換)
//日期的月份不能寫成小寫mm,因為在日期中還有分鐘mm,這兩者不能相同。
1.建立一個類實現Convert介面,實現convert方法
public date convert(String source){
if(source!=null&&!source.equals(""){
SimpleDateFormat sdf=getSimpleDateFormat(source);
return sdf.parse(source);
}
}
public Date getSimpleDateFormat(String source){
SimpleDateFormat sdf=new SimpleDateFormat();
if(Pattern.matches("^//d{4}-//d{2}-//d{2}$",source){
sdf.applayPattern("yyyy-MM-dd");
}else if(Pattern.matches("^//d{4}///d{2}///d{2}$",source){
sdf.applayPattern("yyyy/MM/dd");
}else if(Pattern.matches("^//d{4}//d{2}//d{2}$",source){
sdf.applayPattern("yyyyMMdd");
}
return sdf;
}
2.註冊型別轉換器
<bean id="typeConvert" class="剛才建立的類的路徑"/>//由beanFactory去生成這個類
<bean id="convertionServiceBean" class="convertionServiceFactoryBean的全路徑名">
<!-- <property name="convert">
<set>
<ref bean="typeConvert"/>
<ref bean="typeConvert2"/>
</set>
</property >-->多個轉換型別的寫法
</bean>
<property name="convert" ref="typeConvert"/>//這裡只有一個可以這樣寫
處理器對映器去呼叫convertionServiceBean,當springMVC註解驅動被載入的時候,這個convertionServiceBean給了處理器對映器。所以要新增mvc註解驅動
<mvc:annotation-driven convertion-service="convertionServiceBean"/>