[英]How do I handle an unknown number of RequestParams in Spring Boot REST?
[英]In Spring Boot 2 how can I accept LocalDates as RequestParams
我正在使用 Spring Boot 2.0.0 RC1。 我可以看到這個變化: https : //github.com/spring-projects/spring-boot/commit/2fa0539e7f7bf93505f67303955cc7da6f9f5846和我的類路徑上的 WebConversionService 類。 我可以提供一個帶有我選擇的日期格式的 bean。 然而這個:
@RequestMapping(value = ["/test"], method = [RequestMethod.GET])
fun test2(@RequestParam param: LocalDate): LocalDate {
return param
}
當我用“2018-01-01”調用它時仍然不起作用。 我知道我可以使用 @DateTimeFormat 但我試圖避免這種情況並全局設置格式(或者理想情況下根本不設置它並且讓它正常工作,就像解析 JSON 正文一樣)
對於這個新功能的工作,你需要設置spring.mvc.date-format
屬性在application.properties
。
請注意,使用通用 ISO 格式yyyy-MM-dd
似乎存在問題:當我嘗試使用該格式時,遇到以下異常:
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]
通過調試,我發現根本原因是這個異常:
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
而且我還發現用於解析的DateTimeFormatter
由toString()
:
Value(YearOfEra,4,19,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)
我認為無法獲得LocalDate
的原因是構造的TemporalAccessor
缺少Era
字段的值,但有一個填充的YearOfEra
字段。
所以我嘗試使用uuuu-MM-dd
(請參閱此處了解y
和u
之間的區別),它完美地工作:
spring.mvc.date-format=uuuu-MM-dd
更新
在 GitHub 上打開了一個新問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.