简体   繁体   中英

In Spring Boot 2 how can I accept LocalDates as RequestParams

I'm using Spring Boot 2.0.0 RC1. I can see this change: https://github.com/spring-projects/spring-boot/commit/2fa0539e7f7bf93505f67303955cc7da6f9f5846 and the class WebConversionService on my classpath. I can provide a bean of it with my chosen date format. However this:

@RequestMapping(value = ["/test"], method = [RequestMethod.GET])
fun test2(@RequestParam param: LocalDate): LocalDate {
    return param
}

Still doesn't work when I call it with "2018-01-01". I'm aware I can use @DateTimeFormat but I'm trying to avoid that and set the format globally (or ideally not set it at all and have it just work, like it does for parsing JSON bodies)

For this new feature to work, you need to set the spring.mvc.date-format property in your application.properties .

Note that there seems to be a problem with using the common ISO format yyyy-MM-dd : when I tried with that, I ran into the following exception:

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2018-04-20'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-04-20]

Through debugging, I found that the root cause is this exception:

Text '2018-04-20' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=20, YearOfEra=2018, MonthOfYear=4},ISO of type java.time.format.Parsed

And I also found that the DateTimeFormatter that gets used for parsing is represented like that by toString() :

Value(YearOfEra,4,19,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)

I presume that the reason why a LocalDate could not be obtained is that the TemporalAccessor that gets constructed lacks a value for the Era field, but has a filled YearOfEra field.

So I tried with uuuu-MM-dd instead (see here for the distinction between y and u ), which works perfectly:

spring.mvc.date-format=uuuu-MM-dd

UPDATE

Opened a new issue on GitHub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM