SpringMVC 全局日期轉(zhuǎn)換器的使用

SpringMVC 實(shí)現(xiàn)日期轉(zhuǎn)換器

springmvc 默認(rèn)是不支持字符串直接轉(zhuǎn)換成Date類(lèi)型的,需要通過(guò)其他實(shí)現(xiàn)日期的轉(zhuǎn)換
兩種方式:

1、使用注解

注解方式:
@DateTimeFormat(pattern = "yyyy-MM-dd")
這個(gè)注解加到需要轉(zhuǎn)換的屬性上

但是如果你的項(xiàng)目中又多個(gè)需要做時(shí)間轉(zhuǎn)換的屬性的話,那么使用注解就會(huì)比使用xml配置全局的要繁瑣一些。所以看情況使用哪種方式。

2、實(shí)現(xiàn)Converter接口
  • 使用@Component 注解
    @Component
public class StringToDateConvert implements Converter<String, Date> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String s) {
        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


}
  • 在springmvc.xml文件中注冊(cè)一個(gè)轉(zhuǎn)換器
<!--2.把轉(zhuǎn)換器對(duì)象放入SpringMVC轉(zhuǎn)換器工廠中-->
    <!--2.把轉(zhuǎn)換器對(duì)象放入SpringMVC轉(zhuǎn)換器工廠中-->
    <bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.jsu.web.converter.StringToDateConvert"/>
            </set>
        </property>
    </bean>
  • 將轉(zhuǎn)換器注冊(cè)到注解驅(qū)動(dòng)中
<!--開(kāi)啟注解驅(qū)動(dòng)-->
    <mvc:annotation-driven conversion-service="conversionServiceFactory"/>
  • 測(cè)試
@ResponseBody
    @RequestMapping("/formatConverter")
    public Date formatConverter (Date date)  {
        System.out.println(date);
        return date;
    }

結(jié)尾

本文到這里就結(jié)束了,感謝看到最后的朋友,都看到最后了,點(diǎn)個(gè)贊再走啊,如有不對(duì)之處還請(qǐng)多多指正。
重要的事情說(shuō)三遍: 關(guān)注我 關(guān)注我 關(guān)注我 !!!!
關(guān)注我?guī)憬怄i更多精彩內(nèi)容

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容