java - Spring rest Controller 从查询参数中的 zoneddatetime 中删除加号

标签 java spring-boot controller zoneddatetime

我有UT,顺利通过

    @Test
    public void test() {
        String text1 = "2009-07-10T14:30:01.001Z";
        String text2 = "2009-07-10T14:30:01.001+03:00";
        DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");

        ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(text1, f);
        ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(text2, f);

        System.out.println(zonedDateTime1);
        System.out.println(zonedDateTime2);
    }

输出是

2009-07-10T14:30:01.001Z
2009-07-10T14:30:01.001+03:00

但是,当我尝试在 spring-controller 上使用这个模式时

    @GetMapping
    public ResponseEntity get( @RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
                                               ZonedDateTime start) {
        Dto result = service.get(start);
        return new ResponseEntity(result, getHeaders(), HttpStatus.OK);
    }

它仅在我传递 Z 而不是时区时有效,例如

2009-07-10T14:30:01.001Z

但是当尝试传递时区偏移量时 - 出现错误消息

"Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.ZonedDateTime] for value '2009-07-10T14:30:01.001 03:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2009-07-10T14:30:01.001 03:00]",

我尝试像这样通过 postman 传递请求

POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001+03:00
header: Content-Type application/json

最佳答案

您必须对 url 进行编码当你有像 plus sign 这样的特殊字符时(+)

POST localhost:9080/MyApp/user?start=2009-07-10T14:30:01.001%2B03:00

关于java - Spring rest Controller 从查询参数中的 zoneddatetime 中删除加号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61448838/

相关文章:

php - 尝试打印多维数组中的值以形成预设值

java - 为什么 Java forkbomb 不会导致 StackOverflowError?

java - Path.toFile() 和 new File(pathString) 的不同行为

java - 哪个类加载器将是线程内创建的类加载器的父级?

java - Java中命名实体识别的最大熵马尔可夫模型

spring - 如何在Spring Integration测试之间删除内存中的h2db?

java - getResourceAsStream 返回 NullpointerException

javascript - 如何将数据从 html 发送到 Controller 并重新加载页面

spring-boot - Spring Boot 2.3 Maven Docker 构建添加 "docker.io"前缀

ruby-on-rails - Rails 项目不断崩溃。最新错误: missing :controller key