SpringMVC 請求控制器方法時轉換入參時間,從String轉換成Data

1、使用DateTimeFormat註解,在需要轉換成Data格式的字段或者set方法上添加該註解,使用時可自動轉換,注:每個要轉換的字段都需要各自添加。注:需要在SpringMVC配置文件中設置註解驅動 <mvc:annotation-driven />用於自動裝配需要的bean

 @DateTimeFormat(pattern = "yyyy-MM-dd")
 private Date gdate;

2、使用InitBinder註解和PropertiesEditor,在對應的controller中,添加由@InitBinder註解的方法,在客戶端請求控制器方法時,每次都會調用該方法,如果有要轉換的入參,則調用該方法內註冊的自定義編輯器。

    @InitBinder
    public void initBinder(WebDataBinder binder){
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
        binder.registerCustomEditor(Date.class,editor);
    }

3、實現Converter接口並使用org.springframework.context.support.ConversionServiceFactoryBean或者org.springframework.format.support.FormattingConversionServiceFactoryBean註冊到SpringMVC的配置文件中

定義Converter接口

package converter;
import org.springframework.core.convert.converter.Converter;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * @author: yinzhenying
 * @date: 2020-02-22 20:57
 * @desc:
 */
public class DateConvert implements Converter<String, Date> {

    public Date convert(String text) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }
}

對應的springmvc配置文件中增加

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="converter.DateConvert"></bean>
            </list>
        </property>
    </bean>

或者使用:

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="converter.DateConvert"></bean>
            </list>
        </property>
    </bean>

 

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