我使用 Spring Boot 并在 Maven 中包含 jackson-datatype-jsr310
:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.7.3</version>
</dependency>
当我尝试将 RequestParam 与 Java 8 日期/时间类型一起使用时,
@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"
}
最佳答案
TL;DR - 您可以使用 @RequestParam
将其捕获为字符串,或者您可以让 Spring 通过以下方式将字符串另外解析为 java 日期/时间类参数上也有 @DateTimeFormat
。
@RequestParam
足以获取您在 = 号后提供的日期。但是,它以 String
的形式进入该方法。这就是它抛出强制转换异常的原因。
有几种方法可以实现这一目标:
- 自己解析日期,获取字符串形式的值。
@GetMapping("/test")
public Page<User> get(@RequestParam(value="start", required = false) String start){
//Create a DateTimeFormatter with your required format:
DateTimeFormatter dateTimeFormat =
new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE);
//Next parse the date from the @RequestParam, specifying the TO type as a TemporalQuery:
LocalDateTime date = dateTimeFormat.parse(start, LocalDateTime::from);
//Do the rest of your code...
}
- 利用 Spring 自动解析和期望日期格式的能力:
@GetMapping("/test")
public void processDateTime(@RequestParam("start")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
LocalDateTime date) {
// The rest of your code (Spring already parsed the date).
}
关于spring - 如何在Spring中使用LocalDateTime RequestParam?我得到 "Failed to convert String to LocalDateTime",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274353/