使用Spring @RestController通过ZonedDateTime参数处理HTTP GET


问题内容

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

@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

谢谢!


问题答案:

@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