SpringBoot 表单提交全局日期格式转换器

文章介绍了在SpringBoot中处理前端传入的日期参数的四种方式:实现Converter接口、使用@ControllerAdvice和@InitBinder注解、配置RequestMappingHandlerAdapter。这些方法主要用于将前端提交的日期字符串转换为Date对象,适应不同的Content-Type提交形式。

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

参考资料

  1. SpringBoot–LocalDateTime格式转换(前端入参)
  2. SpringBoot @InitBinder注解绑定请求参数


分析
⏹当前台的提交数据的Content-Type为以下情况

  • application/x-www-form-urlencoded: 表单提交。
  • multipart/form-data: 二进制流提交,多用于上传文件。

的时候,使用此转换方式。

⏹ 会用到全局日期转换工具类DateUtil.formatDateStrToDateAllFormat(),详情可以参考 SpringBoot JSON全局日期格式转换器


一. 实现Converter<S, T>接口的方式

  • 实现SpringConverter接口,指定将String转换为Date
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class GlobalFormStrToDateConvert implements Converter<String, Date> {

    @Override
    public Date convert(String dateStr) {
        try {
            return DateUtil.formatDateStrToDateAllFormat(dateStr);
        } catch (Exception e) {
            return null;
        }
    }
}

二. 全局@ControllerAdvice + @InitBinder注解的方式

  • @ControllerAdvice注解会拦截所有controller请求,配合@InitBinder注解,在参数封装到实体类之前将String日期转换为Date日期
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

@ControllerAdvice
public class GlobalFormStrToDateConvert {

    @InitBinder
    protected void dateStrToDate(WebDataBinder binder) {

        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String dateStr) throws IllegalArgumentException {
                Date date = DateUtil.formatDateStrToDateAllFormat(dateStr);
                setValue(date);
            }
        });
    }
}

三. RequestMappingHandlerAdapter的方式

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.beans.PropertyEditorSupport;
import java.util.Date;

@Configuration
public class GlobalFormStrToDateConvert {

    @Bean
    public RequestMappingHandlerAdapter webBindingInitializer(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
		
		// 通过lombda表达式创建WebBindingInitializer对象
        WebBindingInitializer webBindingInitializer = binder -> binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String dateStr) {
                Date date = DateUtil.formatDateStrToDateAllFormat(dateStr);
                setValue(date);
            }
        });
        requestMappingHandlerAdapter.setWebBindingInitializer(webBindingInitializer);
        return requestMappingHandlerAdapter;
    }
}

四. 效果

⏹前台JS

const jsonData = {
	// 👉待处理的日期字符串数据
    birthday: '20210105',
    nameAA: 'jiafeitian',
    hobby: '吃饭'
};

$.ajax({
    url: '后台url',
    type: 'POST',
    // 对象转换为json字符串
    data: jsonData,
    // 指定为表单提交
    contentType: "application/x-www-form-urlencoded",
    success: function (data, status, xhr) {
        console.log(data);
    }
});

⏹后台Form

import lombok.Data;
import java.util.Date;

@Data
public class Test15Form {

    private String name;

    private String hobby;

    private String address;
	
	// 用来接收的Date类型的数据
    private Date birthday;
}

👇可以看到前台提交的日期字符串被转换为Date格式了

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值