SpringBoot使用LocalDate接收参数解析问题

在接收前端参数时,为了能够最大程度的偷懒,使用过LocalDate来接收了日期,但是发现一个问题。先看代码:

java 复制代码
    @GetMapping("test")
    public Result test(@RequestParam("startDate") LocalDate startDate){}

使用postman测试接口时使用了?startDate=2025/10/10 ,发现可正常工作。但是偶然发现在我的chrome访问相同链接就会报错:Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type

查找原因

使用charles抓包发现请求完全一致不存在转义编码,而且用safari也行。

于是java断点,发现了问题LocalDate转换时:

java 复制代码
    public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
        Objects.requireNonNull(formatter, "formatter");
        return formatter.parse(text, LocalDate::from);
    }

发现了其中的区别:

问题发现

chrome配置的默认语音是英文。中文的默认短日期格式支持 yyyy/M/d,而英文的默认短日期格式为 M/d/yy,其中月在前,年份在后(且通常简化为两位,如 "20" 表示 2020)。例如,对于 2020 年 10 月 10 日,期望的输入是 "10/10/20",只可表示2000-2099年的范围。

解决

所以非常不建议这么书写,还挑访问环境必须不能惯着。正确书写方式,指定:

java 复制代码
    @GetMapping("test")
    public Result test(@RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
     LocalDate startDate){}

ISO默认:

java 复制代码
	/**
	 * Common ISO date time format patterns.
	 */
	enum ISO {

		/**
		 * The most common ISO Date Format {@code yyyy-MM-dd} — for example,
		 * "2000-10-31".
		 */
		DATE,

		/**
		 * The most common ISO Time Format {@code HH:mm:ss.SSSXXX} — for example,
		 * "01:30:00.000-05:00".
		 */
		TIME,

		/**
		 * The most common ISO Date Time Format {@code yyyy-MM-dd'T'HH:mm:ss.SSSXXX}
		 * — for example, "2000-10-31T01:30:00.000-05:00".
		 */
		DATE_TIME,

		/**
		 * Indicates that no ISO-based format pattern should be applied.
		 */
		NONE
	}
相关推荐
用户8356290780513 小时前
使用 Python 操作 PowerPoint 中的图片
后端·python
凤山老林3 小时前
Spring Boot DDD 分层架构落地:领域模型、聚合根与事件驱动的业务实战
java·spring boot·架构
自强的小白3 小时前
MYbatis-plus(自定义sql)
java·sql·mybatis
古法安卓3 小时前
Android-Ext4文件系统问题排查
android·java·android studio
Escalating_xu3 小时前
【C 语言】深入理解指针(3):字符指针、数组指针、二维数组传参、函数指针与转移表
java·c语言·开发语言
对象存储与RustFS3 小时前
自建对象存储的第一个决定:单机就够,还是必须上分布式
后端·rust·开源
不正经的码狗3 小时前
Java 开发环境搭建与 Eclipse 使用速通教程
java·开发语言·eclipse
用户8181870627463 小时前
第37章 Java应用在K8s里的经典坑:容器内存/CPU limit与JVM参数不匹配导致的OOMKilled
java·后端
小小张说故事3 小时前
pandas 读大 CSV 太慢?6 个实测提速技巧(dtype / 分块 / 引擎选择)
后端·python·pandas
马剑威(威哥爱编程)3 小时前
【AI全栈后端12-03】Spring Boot 用多模型路由把智能客服成本降下来
java·人工智能·spring boot