簡體   English   中英

無法將屬性“ dateOfBirth”的類型“ java.lang.String”的屬性值轉換為所需的類型“ java.util.Date”;

[英]Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfBirth';

我正在使用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";
        }

客戶類是:

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

那么,我該如何解決?

當我將類更改為:

@DateTimeFormat(iso=ISO.DATE)
Date dateOfBirth;

看來,這有助於將字符串轉換為更復雜的格式,例如date。 這里

您需要使用@Temporal批注

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM