SpringでLocalDateTime RequestParamを使用するにはどうすればいいですか?「文字列をLocalDateTimeに変換できませんでした」というメッセージが表示されます。質問する

SpringでLocalDateTime RequestParamを使用するにはどうすればいいですか?「文字列をLocalDateTimeに変換できませんでした」というメッセージが表示されます。質問する

私は Spring Boot を使用し、jackson-datatype-jsr310Maven に含まれています:

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

ベストアンサー1

要約- だけで文字列としてキャプチャすることも、パラメータを使用して@RequestParamSpring で文字列をさらに Java の日付/時刻クラスに解析することもできます。@DateTimeFormat

= 記号の後に指定した日付を取得するには で十分です@RequestParam。ただし、メソッドには として入力されますString。そのため、キャスト例外がスローされます。

これを実現するにはいくつかの方法があります。

  1. 日付を自分で解析し、値を文字列として取得します。
@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...
}
  1. 日付形式を自動的に解析して予測する 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).
}

おすすめ記事