【问题标题】:Using Spring @RestController to handle HTTP GET with ZonedDateTime parameters使用 Spring @RestController 处理带有 ZonedDateTime 参数的 HTTP GET
【发布时间】:2015-09-10 22:44:20
【问题描述】:

我正在创建一个端点,它将接收日期以在服务器端进行一些过滤。代码如下所示:

@RequestMapping(
        value = "/test",
        method = RequestMethod.GET,
        produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
)
@ResponseStatus(HttpStatus.OK)
public TestSummaryModel getTestSummaryByDate(
        @RequestParam ZonedDateTime start,
        @RequestParam ZonedDateTime end) {

    return testService.getTestBetween(start, end);

}

当我尝试调用我的端点时,我收到一个 HTTP 400 错误“客户端发送的请求在语法上不正确。”

我尝试了不同的日期格式,但都没有奏效。我错过了什么吗?我读到了@DateTimeFormat,但即使我添加了它,它也不起作用。

@RequestParam @DateTimeFormat(pattern = "dd-MM-yyyy") ZonedDateTime start

这是我正在执行的请求的示例:

http://host/test-api/v1/test-summary/test?start=09-09-2015&end=09-09-2015

谢谢!

【问题讨论】:

    标签: java spring spring-mvc spring-restcontroller


    【解决方案1】:

    @DateTimeFormat 是您所需要的。 Spring MVC 4 为ZonedDateTime 提供了适当的转换器。

    但是,您需要提供适当的模式并发送适当的值。

    dd-MM-yyyy 格式提供的日期信息不足以生成ZonedDateTime

    试试

    @RequestParam("start") @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime start
    

    然后发送

    ...?start=2014-04-23T04:30:45.123Z
    

    或者,使用不需要区域或时间信息的日期类型,并向@DateTimeFormat 提供适当的日期格式。

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 2014-05-24
      • 1970-01-01
      • 2023-03-31
      • 2018-10-16
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多