SpringMVC的自定義類型轉換器之路

在使用SpringMVC從前臺獲取用戶數據然後存入庫中時,有時候會出現類型錯誤,比如輸入日期爲:
2020-04-22,提交時就會報輸入異常,所有我們就要考慮自定義類型轉換器了!

1.首先得實現Converter接口

注意Converter接口在:org.springframework.core.convert.converter.Converter包下

public class StringToDateConverter implements Converter<String, Date> {
    /**
     * source 傳入的字符串
     * @param source
     * @return
     */
    @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("數據類型轉換出現錯誤");
        }
    }
}

2.然後在ConversionServiceFactoryBean中注入我們定義的轉換器(web.xml文件中)

 <!-- 配置自定義類型轉換器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.itt.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>

3.最後開啓SpringMVC對於類型轉換的支持

<mvc:annotation-driven conversion-service="conversionService"/>

這樣我們就實現了類型的轉換!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章