SpringMVC 自动绑定数据 - DATE多个类型格式 的数据绑定

本文介绍三种在SpringMVC中实现多种日期格式自动绑定的方法:通过实体类注解、控制器内InitBinder方法及自定义日期编辑器。

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

总共方法有三种:

第一种:繁重操作解决方式:

在 Controller 里面不写 InitBinder 方法; 直接在请求实体类里面将DATE 类型的字段 注解 @DateTimeFormat("格式")


第二种:比较繁重操作解决方式:

在 Controller 里面写 InitBinder 方法; 里面写多个日期格式;将特殊的标出;如下代码:

@InitBinder
    public void initBinder(WebDataBinder b) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        b.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
        
        DateFormat df2 = new SimpleDateFormat("yyyy-MM");
        String[] fileds = {"字段名", "字段名", "字段名"};
        for(String filed : fileds){
            b.registerCustomEditor(Date.class, filed, new CustomDateEditor(df2, true));
        }
    }

第三种:轻松解决方式:

自己写一个DATE数据绑定类;然后在Controller 里面写 InitBinder 方法里面应用;如下代码

package com.luwen.dai.util;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpecialDateEditor extends PropertyEditorSupport {
    
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            //防止空数据出错
            if(StringUtils.isNotBlank(text)){
                date = format.parse(text);
            }
        } catch (ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = format.parse(text);
            } catch (ParseException e1) {
                format = new SimpleDateFormat("yyyy-MM");
                
                try{
                    date = format.parse(text);
                }catch (Exception e2) {
                    logger.error("自动绑定日期数据出错", e);
                }
            }
        }
        setValue(date);
    }
    
}

然后在initBinder 方法里直接引用

@InitBinder
    public void initBinder(WebDataBinder b) {
        b.registerCustomEditor(Date.class, new SpecialDateEditor());
    }

 以上为 三种 SpringMVC 多个 日期格式 数据类型自动绑定解决方法;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值