Spring数据转换(二)-- @InitBinder

本文介绍了如何在Spring框架中利用JDK自带的PropertyEditor来实现数据类型的转换,特别是针对日期类型的处理方式。通过继承PropertyEditorSupport并重写setAsText方法,可以轻松地将字符串转换为Date对象。

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

Spring支持Jdk提供的PropertyEditor实现数据类型的转换。相比于Spring提供的数据转换,PropertyEditor的使用相对简单,不需要在xml文件中配置什么。

首先继承PropertyEditorSupport实现其中的setAsText方法

public class DateEditor extends PropertyEditorSupport {
    // 将传如的字符串数据转换成Date类型
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(text);
            setValue(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

同时在Controller中添加如下的代码:

// 在控制器初始化时注册属性编辑器
@InitBinder
public void initBinder(WebDataBinder binder){
    // 注册自定义编辑器,将方法传入的Dateleixng 使用 DateEditor进行转换
    binder.registerCustomEditor(Date.class, new DateEditor());
}

@InitBinder会在控制器初始化时注册属性编辑器,WebDataBinder对象用于处理请求消息和处理方法的绑定工作。

转载于:https://www.cnblogs.com/arax/p/8551839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值