如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime的信息"; [英] How to use LocalDateTime RequestParam in Spring? I get "Failed to convert String to LocalDateTime"
问题描述
我使用Spring Boot并将jackson-datatype-jsr310
包含在Maven中:
I use Spring Boot and included jackson-datatype-jsr310
with Maven:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.7.3</version>
</dependency>
当我尝试使用Java 8日期/时间类型的RequestParam时,
When I try to use a RequestParam with a Java 8 Date/Time type,
@GetMapping("/test")
public Page<User> get(
@RequestParam(value = "start", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start) {
//...
}
并使用以下URL进行测试:
and test it with this 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额外解析该字符串也可以通过参数上的@DateTimeFormat
转换为Java日期/时间类.
TL;DR - you can capture it as a string with just @RequestParam
, or you can have Spring additionally parse the string into a java date / time class via @DateTimeFormat
on the parameter as well.
@RequestParam
足以在=符号后获取您提供的日期,但是,它作为String
进入方法.这就是为什么它引发强制转换异常的原因.
the @RequestParam
is enough to grab the date you supply after the = sign, however, it comes into the method as a String
. That is why it is throwing the cast exception.
有几种方法可以做到这一点:
There are a few ways to achieve this:
- 自己解析日期,以字符串的形式获取值.
@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中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime的信息";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!