2017-05-25 33 views
0

在我的春天MVC應用程序,我有一個模型,僱員有一個LocalDate字段dateOfBirth。我將模型從ModelAndView對象的控制器發送到我的jsp。這裏dateOfBirth不是用jsp打印的,而且拋出了下面的異常。要轉換的源必須是java.lang.String的實例;相反,它是一個java.time.LocalDate

要轉換的源必須是java.lang.String的實例;相反,它是一個java.time.LocalDate

這是我的jsp片段顯示我的模型對象。

<form:form id="employeeForm" modelAttribute="command" action="${addEmployee}" method="POST"> 
      <table> 
       <tr> 
        <td>Name: </td> 
        <td><form:input path="name"/></td> 
       </tr> 
       <tr> 
        <td>Date of Birth: </td> 
        <td><form:input path="dateOfBirth"/></td> 
       </tr> 
       <tr> 
        <td>Designation: </td> 
        <td><form:input path="designation"/></td> 
       </tr> 
       <tr> 
        <td colspan="2"><input type="submit" value="Submit"/></td> 
       </tr> 
      </table> 
     </form:form> 

此外,我發送日期在適當的格式,因此不需要解析它。唯一的問題是將日期顯示爲字符串。

回答

-1

您應該定義轉換器以便讓Spring將您的HMTL輸入的字符串轉換爲Java對象。我發現這篇文章,我認爲這可以幫助你:JSP form date input field

問候!

+0

這並不完全回答這個問題,你應該包括一些示例代碼。請參閱:[如何編寫一個好的答案?](https://stackoverflow.com/help/how-to-answer) – CodingNinja

+0

嗨..這種方法工作正常從jsp輸入控制器。但是當數據從控制器傳遞給jsp時,它仍然不起作用。現在引發另一個錯誤消息「無法從LocalDate轉換爲日期」。在InitiBinder中,我使用LocalDate進行綁定。 – Sriram

0

您應該在您的模型類屬性dateOfBirth中使用@DateTimeFormat註釋以您所需的日期格式。

例子:

import org.springframework.format.annotation.DateTimeFormat; 

@DateTimeFormat(pattern = "dd-MM-yyyy") 
private LocalDate dateOfBirth; 

您可以將@DateTimeFormat註釋java.util.Date,java.util.Calendar中,java.lang.Long中,喬達時間值類型;從Spring 4和JDK 8到JSR-310 java.time類型。

查看API Reference瞭解更多。

+0

我已經在我的模型類中應用了註釋,並且它在後端工作正常。當我嘗試在jsp中顯示它時,拋出「無法從LocalDate轉換爲日期」錯誤。另外,當我直接在jsp上打印LocalDate時,它工作正常。但是我無法從命令對象中顯示它。 – Sriram

0

將您的LocalDate對象轉換爲字符串,然後將其打印出來。

LocalDate localDate = LocalDate.now();//For reference 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy"); 
String formattedString = localDate.format(formatter); 

應打印5月26日2017年

+0

這也是我的嘗試。我改變了我的getter方法以字符串形式返回LocalDate字段。即使這樣我在jsp頁面中也遇到了同樣的錯誤。 – Sriram

相關問題