小编典典

如何在Spring中使用LocalDateTime RequestParam?我收到“无法将String转换为LocalDateTime”

spring-boot

我使用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) {
//...
}

并使用以下网址进行测试:

/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"
}

阅读 1264

收藏
2020-05-30

共1个答案

小编典典

TL; DR-
您可以使用just捕获它为字符串@RequestParam,也可以让Spring也通过@DateTimeFormat参数另外将字符串解析为java日期/时间类。

@RequestParam足以抓住你等号(=)后提供的日期,但是,它涉及到的方法作为String。这就是为什么它引发强制转换异常。

有几种方法可以实现此目的:

  1. 自己解析日期,以字符串的形式获取值。

    @GetMapping(“/test”)
    public Page 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...
    

    }

  2. 利用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).
    }

2020-05-30