无法转换类型' java.lang.String'的属性值要求的类型' java.util.Date'对于财产" dateOfBirth&#39 ;;

时间:2016-12-21 07:49:42

标签: java spring thymeleaf

我正在使用spring mvc和Thymeleaf。这是datetime-picker的html表单:

<form action="#" th:action="@{/created}" th:object="${customer}" method="post" class="form-horizontal">    
<div class="row edit-form">
        <label for="name" class="col-sm-2 control-label text-right">Date of Birth</label>
        <div class="col-sm-6">
            <input type="date" class="form-control"    
            th:field="*{dateOfBirth}" th:required="required" id="dateOfBirth"/>
        </div>
    </div>
</form>

在控制器中我有:

  @RequestMapping(value ="/created",method = RequestMethod.POST)
        public String  submitNewCustomer(@ModelAttribute Customer customer){
            customerService.createNewCustomer(customer);
            return "edit";
        }

,Customer类是:

@Data
@Entity
public class Customer {

    @Id
    @GeneratedValue
    Long id;

    String firstname;
    String lastname;
@Temporal(TemporalType.TIMESTAMP)
    Date dateOfBirth;
    String username;
    String password;

}

不幸的是,当我提交表格时,它抱怨:

Field error in object 'customer' on field 'dateOfBirth': rejected value [2016-12-14]; codes [typeMismatch.customer.dateOfBirth,typeMismatch.dateOfBirth,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [customer.dateOfBirth,dateOfBirth]; arguments []; default message [dateOfBirth]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfBirth'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Temporal java.util.Date] for value '2016-12-14'; nested exception is java.lang.IllegalArgumentException]

那么,我该如何解决呢?

2 个答案:

答案 0 :(得分:3)

当我将课程改为:

时,问题就解决了
@DateTimeFormat(iso=ISO.DATE)
Date dateOfBirth;

看起来,它有助于将字符串转换为更复杂的格式,如日期。 请参阅here

答案 1 :(得分:1)

您需要使用@Temporal注释

@Temporal(TemporalType.TIMESTAMP)
private java.util.Date dateOfBirth;