Using Spring @RestController to handle HTTP GET with ZonedDateTime parameters

戏子无情 提交于 2019-12-23 08:28:40

问题


I'm creating an endpoint that will receive dates to do some filtering in the server side. The code looks like this:

@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);

}

When I try to invoke my endpoint I get an HTTP 400 error "The request sent by the client was syntactically incorrect."

I have try different date formats but none of them worked. Am I missing something? I read about the @DateTimeFormat but even though I added it, was not working.

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

This is an example of the request I'm doing:

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

Thanks!


回答1:


@DateTimeFormat is what you need. Spring MVC 4 has the appropriate converters for ZonedDateTime.

However, you need to provide an appropriate pattern and send an appropriate value.

The information provided in a date formatted as dd-MM-yyyy is not enough to produce a ZonedDateTime.

Try

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

and send

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

Alternatively, use a date type that doesn't need zone or time information and provide an appropriate date format to @DateTimeFormat.



来源:https://stackoverflow.com/questions/32512782/using-spring-restcontroller-to-handle-http-get-with-zoneddatetime-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!