springmvc Date类型的转换

本文介绍三种在Spring MVC中处理日期参数的方法:通过@initBinder注册自定义编辑器、实现Converter接口进行全局配置及实现Formatter接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:通过@initBinder数据绑定来实现

    @RequestMapping(value = "date1.do")
    public @ResponseBody String date1(Date date1){
        return date1.toString();
    }

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

方法二:实现Converter接口全局配置

MyDateConverter类

public class MyDateConverter implements Converter<String,Date> {
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

xml配置文件

<mvc:annotation-driven conversion-service="myDateConverter"/>
<bean id ="myDateConverter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       <property name="converters">
           <set>
               <bean class="com.common.MyDateConverter"></bean>
           </set>
       </property>
</bean>

Test类

    @RequestMapping(value = "date2.do")
     public @ResponseBody String date2(Date date2){
        return date2.toString();
    }

方法三:实现Formatter接口
MyDateFormatter类

public class MyDateFormatter implements Formatter<Date> {
    public Date parse(String text, Locale locale) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(text);
    }
    public String print(Date object, Locale locale) {
        return null;
    }
}

XML全局配置文件

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

<bean id ="MyDateFormatter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="formatters">
            <set>
                <bean class="com.common.MyDateFormatter"></bean>
            </set>
        </property>
</bean>

Test测试类

    @RequestMapping(value = "date2.do")
     public @ResponseBody String date2(Date date2){
        return date2.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值