spring自动绑定多种date类型格式

本文介绍了三种在Spring MVC中处理日期格式化的实用方法,包括直接使用注解、编写自定义编辑器以及创建通用的日期绑定类,帮助开发者高效地解决日期格式问题。

摘要生成于 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());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值