我使用 Spring Boot 并将 jackson-datatype-jsr310
包含在 Maven 中:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.7.3</version>
</dependency>
当我尝试使用具有 Java 8 日期/时间类型的 RequestParam 时,
@GetMapping("/test")
public Page<User> get(
@RequestParam(value = "start", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start) {
//...
}
并使用此 URL 对其进行测试:
/test?start=2016-10-8T00:00
我收到以下错误:
{
"timestamp": 1477528408379,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
"message": "Failed to convert value of type [java.lang.String] to required type [java.time.LocalDateTime]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2016-10-8T00:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-10-8T00:00]",
"path": "/test"
}
原文由 Kery Hu 发布,翻译遵循 CC BY-SA 4.0 许可协议
TL;DR - 您可以仅使用
@RequestParam
将其捕获为字符串,或者您也可以让 Spring 通过@DateTimeFormat
在参数上将字符串另外解析为 java 日期/时间类.@RequestParam
足以获取您在 = 符号后提供的日期,但是,它作为String
进入方法。这就是它抛出强制转换异常的原因。有几种方法可以实现这一点: