6自定義類型轉換器

一
java->Package->cn.itcast.utils
utils->StringToDateConverter.java


二 springmvc.xml


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

    <!--開始spirngMVC框架註解的支持-->
    <mvc:annotation-driven conversion-service="conversionService"/>

三utils->StringToDateConverter.java
package cn.itcast.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 把字符串轉換爲日期
* */
public class StringToDateConverter implements Converter<String,Date> {
    /*
    * String source  傳入進來字符串
    * @param source
    * @return
    * */
    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("數據類型轉換出現錯誤");
        }

    }
}

三 param.jsp文件這樣寫
    <form action="param/saveUser" method="post">
        用戶姓名:<input type="text" name="uname"/><br>
        用戶年齡:<input type="text" name="age"/><br>
        用戶生日:<input type="text" name="date"/><br>
        <input type="submit" name="提交"/>
    </form>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章