SpringMVC数据绑定之数据装换

对于一些URL中传过来的参数,而接口无法按我们想要的格式来进行接收,这些可以使用如下的方法。

如URL带有时间的参数,以字符类型传参,而接口中想使用Date类型接收,这时就需要做一些处理。

@RequestMapping("date")
@ResponseBody
public String date(Date date) {
    return date.toString();
}

浏览器输入:http://localhost:8080/date?date=2018-12-21 22:13:22

一、使用PropertyEditor

@InitBinder("date")
public void initDate(WebDataBinder webDataBinder) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    CustomDateEditor customDateEditor = new CustomDateEditor(sdf, true);
    webDataBinder.registerCustomEditor(Date.class, customDateEditor);
}

返回:Fri Dec 21 22:13:22 CST 2018

注:SpringMVC中提供了很多的PropertyEditor的实现类,CustomDateEditor就是其中之一,它提供了时间格式的数据转换方法。将其注册到binder中,可实现时间参数的接收转换。

二、使用Formatter

InitBinder只能在当前的Controller中使用,如果多个Controller需要使用同样的时间转换,就需要提供能全局使用的方法。

实现Formatter接口

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

spring-mvc.xml中增加配置

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

<mvc:annotation-driven conversion-service="myDateFormatter" />
返回:Fri Dec 21 22:13:22 CST 2018

注:anotation-driven中需增加conversion-service配置,否则将不生效

三、使用Converter

熟悉Converter接口

public class MyDateConverter implements Converter<String, Date> {
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
spring-mvc.xml中增加配置

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

返回:Fri Dec 21 22:13:22 CST 2018


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值