Spring Boot Date conversion from Form

喜欢而已 提交于 2021-01-28 11:57:37

问题


I'm having a few issues with getting a date from a controller because I don't understand what's the right format for it to work.

Controller:

@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:

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

When I submit the form it always gives me an error no matter what the format of the date is :( Here is the error:

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]

If I specify the @DateTimeFormat annotation I thought that the conversion would be done automatically.


回答1:


In YYYY-MM-DD pattern Y is a week year and D is day in a year as per SimpleDateFormat javadoc. For standard dates the pattern should be yyyy-MM-dd:

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

or if you want to use DateTimeFormat.ISO enum:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 



回答2:


My advice is to never let the client send formatted dates. Just think about time zones, are you sure all your frontends are in the same timezones? Or why should the frontend care of formatting a date at all? It should care about displaying.

My suggestion is that the backend only accepts Longs. The conversion is performed by the client and sent as a long. In this way it is not ambiguous at all, and you can treat the long as you like.



来源:https://stackoverflow.com/questions/53188464/spring-boot-date-conversion-from-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!