【问题标题】:Spring MVC GET request with Java 8 Instant request parameter带有 Java 8 Instant 请求参数的 Spring MVC GET 请求
【发布时间】:2017-12-04 17:19:05
【问题描述】:

我正在尝试编写一个将 Java 8 Instant 作为请求参数的 Spring MVC GET 控制器:

    @GetMapping
    @JsonView(OrderListing.class)
    @Validated
    public WebSeekPaginatedResultsDto<OrderListingDto> findAll(@Valid OrderSearchCommand orderSearchCommand) {
       // Some code
    }

与:

    public class OrderSearchCommand {
        private Instant dateCreatedStart;
        private Instant dateCreatedEnd;
        // Some other fields
    }

我正在从一些 React/Javascript 代码中触发一个 GET 请求:

    http://localhost:8080/mms/front/orders?dateCreatedStart=2017-05-31T22%3A00%3A00.000Z 

Spring 似乎不喜欢它并抛出错误。这是错误消息:

    Failed to convert property value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart'; 
    nested exception is java.lang.IllegalStateException: 
    Cannot convert value of type 'java.lang.String' to required type 'java.time.Instant' for property 'dateCreatedStart': no matching editors or conversion strategy found

知道我为什么会得到这个吗?

谢谢

【问题讨论】:

  • 您收到的参数是String 类型,您正尝试将其存储在Instant 中。您必须将String 转换为Instant
  • 您必须使用@DateTimeFormat 注释字段,如duplicate link 所示。
  • 如果 Instant 不适用于“重复”帖子,请查看 spring 参考 (docs.spring.io/spring/docs/current/spring-framework-reference/…) 中的第 9.5 节。第 9.5.5 节介绍了自定义转换器的注册。
  • @Andreas 我重新提出了这个问题,因为我相信@DateTimeFormat 不适用于InstantInstant 未列在 Spring 4 参考文档中此注解支持的类型中。
  • @DwB 啊哈,我刚才看了DateTimeFormat的javadoc,上面写着"JSR-310 java.time types",你说的没错,源代码Jsr310DateTimeFormatAnnotationFormatterFactory 只列出了 6 种类型:LocalDate、LocalTime、LocalDateTime、ZonedDateTime、OffsetDateTime、OffsetTime。

标签: java spring spring-mvc java-8 java.time.instant


【解决方案1】:

错误信息不言自明: 没有注册StringInstant 的转换器。

Controller收到请求时,所有参数都是Strings。 Spring/Jackson 列出了大多数基本类型的预定义转换器: - 字符串 > 整数 - 字符串 > 布尔值

但是没有默认的 String > Instant 转换器。

您需要创建并注册一个。或者您可以将输入类型更改为 Spring 可以使用 @DateTimeFormat 注释处理的内容: How to accept Date params in a GET request to Spring MVC Controller?

【讨论】:

  • 谢谢@Tim,我会检查一下,看看它是否有效
【解决方案2】:

我怀疑@DateTimeFormat 不适用于Instant 字段。 具体来说, Instant 在 Spring 参考文档中未列为它适用的类型之一。

查看Spring Reference Section 9.5 了解有关 Spring 自定义类型转换的详细信息。 创建一个Converter&lt;String, Instant&gt; 转换器。 第 9.5.5 节介绍了自定义类型转换器注册。

【讨论】:

    【解决方案3】:

    也许这可以帮助你? serialize/deserialize java 8 java.time with Jackson JSON mapper我看到这个 Jackson 包含 Instant 课程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 2015-02-27
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      相关资源
      最近更新 更多