Spring 在所需的查询参数上启动 @DateTimeFormat

问题描述

当使用@DateTimeFormat 注解格式化作为查询参数(@RequestParam)发送的日期时,它会自动将空字符串(作为日期接收)转换为 null,而不会抛出类型不匹配异常。当日期参数是可选的时,这可以正常工作,但是,当设置 required = true 时,@DateTimeFormat 接受空字符串并将其转换为 null 而不抛出异常,因此不考虑 required = true spring 属性。这是 Spring 的正常行为吗?是否有任何属性可以传递给@DateTimeFormat 以选择是否可以接受空字符串?

@RequestParam(required = true) @DateTimeFormat(pattern ="yyyy-MM-dd") Date inputDate
        

解决方法

我已尝试在 spring boot 2.4.4 中使用以下代码重现您的问题:

@GetMapping("/")
@ResponseBody
public String demo(@RequestParam(required = true) @DateTimeFormat(pattern = "yyyy-MM-dd") Date inputDate) {
   System.out.println("inputDate: " + inputDate);
   return inputDate.toString();
}
  1. 网址 http://localhost:8080/?inputDate=2021-03-01 在浏览器中给出 Mon Mar 01 00:00:00 CET 2021
  2. 网址 http://localhost:8080/?inputDate=http://localhost:8080/ 在浏览器中给出 There was an unexpected error (type=Bad Request,status=400).,在日志中给出 Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Date parameter 'inputDate' is not present]
  3. 网址 http://localhost:8080/?inputDate=x 在浏览器中给出 There was an unexpected error (type=Bad Request,status=400).,在日志中给出 Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'

根据您的问题,我明白这就是您想要的。

如果我误解了您的问题,请您澄清一下,或者看看您是否可以重现我的结果并查看它们是否提供您想要的行为?

,

尝试使用不带任何 java.time.LocalDate@DateTimeFormat

java.util.Date 已过时,java.time.* 旨在取代它。

LocalDate 默认使用 ISO8601 格式,它与您的 'yyyy-mm-dd' 匹配。 此外,它的 parse 方法对空字符串抛出异常。