无法将java.lang.String类型的属性值转换为必需类型java.util.Date [英] Failed to convert property value of type java.lang.String to required type java.util.Date
本文介绍了无法将java.lang.String类型的属性值转换为必需类型java.util.Date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在表单中输入日期时,我收到此错误。
I'm getting this error when I try to input a date in a form.
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>
...
在控制器中,我写了以下同样的错误(和不同的格式如yyyy / MM / dd)
In the controller I wrote the following with the same error (and different formats like "yyyy/MM/dd")
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
我还尝试在类中添加注释(以及不同的格式),但是相同的错误
I also tried to add annotation in class (as well with different formats) but same error
...
@Column(name = "deadline")
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date deadline;
...
推荐答案
控制器。将dateFormat更改为您的区域设置首选项。
Add this in the controller. Change the dateFormat to your locale preference.
@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor( Date.class,
new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true, 10));
}
考虑在模型中使用此注释(适应您的首选项的适应格式和TemporalType)
Consider using this annotations in your model (Adapting format and TemporalType for your preferences)
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
这篇关于无法将java.lang.String类型的属性值转换为必需类型java.util.Date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文