【问题标题】:Spring boot @DateTimeFormat on required query parametersSpring boot @DateTimeFormat 上所需的查询参数
【发布时间】:2021-06-25 05:47:10
【问题描述】:

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

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

【问题讨论】:

    标签: java spring spring-boot date date-formatting


    【解决方案1】:

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

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

    LocalDate默认使用ISO8601格式,和你的'yyyy-mm-dd'匹配。 此外,它的 parse 方法会在空字符串上引发异常。

    【讨论】:

      【解决方案2】:

      我已尝试使用 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'

      根据您的问题,我知道这就是您想要的。

      如果我误解了你的问题,你能否澄清一下,或者看看你是否可以重现我的结果,看看他们是否给出了你想要的行为?

      【讨论】:

      • 我正在使用 2.2.0.RELEASE 并且您的代码使用此路径:localhost:8080/?inputDate= 返回 inputDate: null 这意味着所需的 true 不起作用
      • Strenge... 你能不能测试一下将 spring-boot-starter-paren 升级到 2.2.4 看看是否有什么不同。它可以是您项目中的任何其他设置吗?只是为了确保您可以尝试来自start.spring.io 的新项目。您在哪个 javaversion 中看到此问题。我用 jdk11 试过了。
      • 我尝试了一个单独的应用程序,它适用于两个春季版本,也许它是我项目下的一个属性。有什么东西会影响这种行为吗?
      • 我正在使用 java 8
      • 很高兴听到它在单独的应用程序中工作。您可以开始检查您的application.properties 是否有任何看似相关的内容。您也可以尝试删除application.properties 的所有内容,看看是否有帮助。如果是这样,你可以一点一点地添加东西,看看它什么时候坏了,以确定麻烦制造者。
      猜你喜欢
      • 2021-09-15
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多