Spring 从表格转换启动日期

Spring Boot Date conversion from Form

我在从控制器获取日期时遇到了一些问题,因为我不明白什么是正确的工作格式。

控制器:

@RequestMapping(value = "/findFlights", method = RequestMethod.POST)
    public String findFlights(@RequestParam("from") String from, @RequestParam("to") String to,
            @RequestParam("departureDate") @DateTimeFormat(pattern = "YYYY-MM-DD") LocalDate departureDate, Model model) {}

形式:

<form th:action="@{/findFlights}" method="POST">
        From:<input type="text" name="from" required/>
        To:<input type="text" name="to" required/>
        Departure Date:<input type="date" name="departureDate"  required />
        <input type="submit" value="Search"/>
</form>

当我提交表单时,无论日期的格式是什么,它总是给我一个错误:( 这是错误:

Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; 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.LocalDate] for value '2018-11-05'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2018-11-05]

如果我指定 @DateTimeFormat 注释,我认为转换会自动完成。

YYYY-MM-DD 模式中,Y 是一年中的一周,D 是一年中的一天,根据 SimpleDateFormat javadoc。对于标准日期,模式应为 yyyy-MM-dd:

@DateTimeFormat(pattern = "yyyy-MM-dd")

或者如果你想使用 DateTimeFormat.ISO 枚举:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)