gpt4 book ai didi

spring-mvc - 如何使用Spring MVC @RequestParam解析不同的ISO日期/时间格式

转载 作者:行者123 更新时间:2023-12-02 13:23:16 28 4
gpt4 key购买 nike

我们的Rest API被多个外部团体使用。它们都使用“ISO-ish”格式,但是时区偏移量的格式略有不同。这些是我们看到的一些最常见的格式:

  • 2018-01-01T15:56:31.410Z
  • 2018-01-01T15:56:31.41Z
  • 2018-01-01T15:56:31Z
  • 2018-01-01T15:56:31+00:00
  • 2018-01-01T15:56:31+0000
  • 2018-01-01T15:56:31+00

  • 在 Controller 中,我使用以下注释:
    @RequestMapping(value = ["/some/api/call"], method = [GET])
    fun someApiCall(
    @RequestParam("from")
    @DateTimeFormat(iso = ISO.DATE_TIME)
    from: OffsetDateTime
    ) {
    ...
    }

    它可以很好地解析变体1-4,但对于变体5和6会产生400 Bad Request错误,但有以下异常(exception):
    Caused by: java.time.format.DateTimeParseException: Text '2018-01-01T13:37:00.001+00' could not be parsed, unparsed text found at index 23
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

    如何使其接受所有上述ISO格式变体(即使它们不100%兼容ISO标准)?

    最佳答案

    我通过添加自定义格式器注释解决了它:

    @Target(AnnotationTarget.VALUE_PARAMETER)
    @Retention(AnnotationRetention.RUNTIME)
    annotation class IsoDateTime

    加上FormatterFactory:
    class DefensiveDateTimeFormatterFactory : 
    EmbeddedValueResolutionSupport(), AnnotationFormatterFactory<IsoDateTime>
    {
    override fun getParser(annotation: IsoDateTime?, fieldType: Class<*>?): Parser<*> {
    return Parser<OffsetDateTime> { text, _ -> OffsetDateTime.parse(text, JacksonConfig.defensiveFormatter) }
    }

    override fun getPrinter(annotation: IsoDateTime, fieldType: Class<*>): Printer<*> {
    return Printer<OffsetDateTime> { obj, _ -> obj.format(DateTimeFormatter.ISO_DATE_TIME) }
    }

    override fun getFieldTypes(): MutableSet<Class<*>> {
    return mutableSetOf(OffsetDateTime::class.java)
    }
    }

    实际的DateTimeFormat类来自我的另一个问题 How to parse different ISO date/time formats with Jackson and java.time?

    并使用WebMvcConfigurer将其添加到Spring:
    @Configuration
    open class WebMvcConfiguration : WebMvcConfigurer {
    override fun addFormatters(registry: FormatterRegistry) {
    registry.addFormatterForFieldAnnotation(DefensiveDateTimeFormatterFactory())
    }
    }

    关于spring-mvc - 如何使用Spring MVC @RequestParam解析不同的ISO日期/时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216335/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com