Spring:无法从类型[java.lang.String]转换为类型[@ org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime]

时间:2017-12-14 18:10:30

标签: java spring spring-mvc java-time

我有一个运行Spring MVC和Thymeleaf的Spring Boot应用程序。其中一个实体是date实体,其中包含LocalDateTime类型的字段@Entity public class Purchase { // Other fields @DateTimeFormat(pattern = "dd-MM-yyyy") private LocalDateTime date; // Getters and setters }

@DateTimeFormat

请注意,此字段已添加pattern注释,指定dd-MM-yyyy form.html,其恰好与我的<form id="purchaseForm" th:action="@{/purchases/(form)}" th:object="${purchase}" action="#" method="post" class="form-horizontal"> <!-- Purchase's date --> <div class="form-group"> <label class="control-label col-sm-2" for="text">Date</label> <input class="col-sm-10" type="text" id="date" th:field="*{date}" th:class="${#fields.hasErrors('date')} ? 'field-error'"/> </div> </form> 中定义的相同:

14-12-2017

给定日期的格式为PurchaseController。 然后,提交后@Controller @RequestMapping("/purchases") public class PurchaseController { @PostMapping(params = "form") public ModelAndView create(@Valid Purchase purchase, BindingResult result, RedirectAttributes redirect) { // Do stuff } } 处理此表单:

Field error in object 'purchase' on field 'date': rejected value [12-12-2017]; 
codes [typeMismatch.purchase.date,typeMismatch.date,typeMismatch.java.time.LocalDateTime,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [purchase.date,date]; arguments []; default message [date]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'date';
nested exception is org.springframework.core.convert.ConversionFailedException: 
Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '12-12-2017'; 
nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [12-12-2017]]

提交后,我收到以下错误:

'12-12-2017'

我不太明白原因,因为被拒绝的值@DateTimeFormat遵循我在@DateTimeFormat注释中定义的模式。此外,java.time的javadoc告诉我们它适用于SDL_Log("%s has %i hp out of %i", player1.name, player1.health, player1.maxhealth); 个新类型。

有什么想法吗?提前谢谢。

0 个答案:

没有答案