109

私は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"
}
4

13 に答える 13

93

TL;DR - だけで文字列としてキャプチャできます。または、Springでパラメーターを@RequestParam介して文字列を 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).
}
于 2016-10-27T04:57:26.803 に答える