Thymelaf拒绝无效日期



我有这个html代码:

<input class="form-control col-sm-8" type="date" th:field="*{completiondate}">

这种型号:

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
public class EventReport {
private Long id;
private Date creationdate;
private String status;
private Date completiondate;
...
}

完成日期不是必需值,有时可能为null。当用户提交邮寄表格时,我采取以下

字段上对象"treeTrimsEventReport"中的字段错误"completiondate":拒绝的值[];

很明显,当我选择日期值时没有错误,应用程序运行良好。我怎样才能在没有错误的情况下在完成日期给出null?

我认为这是一个绑定错误。

您需要告诉spring如何将作为文本(String(的表单数据转换为模型中的类型(这里是Date(。

您可以在EventReport:中的字段上使用此注释进行此操作

import org.springframework.format.annotation.DateTimeFormat
...
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date completiondate;

(更改图案以匹配您希望向用户显示的图案(

Spring提供了另一个选项来告诉它如何绑定数据。

请参阅本章中的参考手册,了解所有选项:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann initbinder

最新更新