无法将java.lang.String类型的属性值转换为必需类型java.util.Date

时间:2014-05-16 18:14:06

标签: java spring date data-binding date-format

当我尝试在表单中输入日期时,我收到此错误。 enter image description here

TaskController

@RequestMapping(value = "/docreatetask", method = RequestMethod.POST)
public String doCreateTask(Model model, @Valid Task task,
        BindingResult result, Principal principal,
        @RequestParam(value = "delete", required = false) String delete) {
    System.out.println(">TaskController doCreateTask " + task);

    if (result.hasErrors()) {
        System.out.println("/docreatetask in here");
        model.addAttribute("task", task);
        System.out.println("+++++"+task.getDeadline());// deadline is null  
        return "createtask";
    }
        ...

Create.jsp

...
<form:form method="POST"
action="${pageContext.request.contextPath}/docreatetask"
commandName="task">
<table class="formtable">
    <tr>
        <td class="label">Task</td>
        <td><form:input cssClass="control" path="taskname"
            name="taskname" type="text" /><br />
                <form:errors path="taskname" cssClass="error" /></td>
        </tr>
    <tr>
        <td class="label">Description</td>
        <td><form:textarea cssClass="control" path="description"
            name="description"></form:textarea><br />
                    <form:errors path="description" cssClass="error" /></td>
    </tr>
    <tr>
        <td class="label">Deadline (dd/mm/yyyy)</td>
        <td><form:input cssClass="control" path="deadline"
            name="deadline" type="date" /><br />
                <form:errors path="deadline" cssClass="error"></form:errors></td>
    </tr>
        ...

在控制器中我写了以下相同的错误(和不同的格式,如&#34; yyyy / MM / dd&#34;)

@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    dateFormat.setLenient(false);
    webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

我还尝试在类中添加注释(以及不同的格式)但是同样的错误

​    ...
    @Column(name = "deadline")
    @DateTimeFormat(pattern = "dd/MM/yyyy")
    private Date deadline;
   ...

3 个答案:

答案 0 :(得分:19)

在控制器中添加它。将dateFormat更改为您的区域设置首选项。

@InitBinder     
public void initBinder(WebDataBinder binder){
     binder.registerCustomEditor(       Date.class,     
                         new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true, 10));   
}

考虑在模型中使用此注释(根据您的偏好调整格式和TemporalType)

@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)

答案 1 :(得分:8)

只需添加@DateTimeFormat(pattern =“yyyy-MM-dd”)( - )

示例:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateNaissance;

答案 2 :(得分:0)

@DateTimeFormat(pattern = "yyyy-MM-dd")

以此替换格式。