Java 在spring中将日期从jsp传递给控制器
我有一张表格:Java 在spring中将日期从jsp传递给控制器,java,spring,Java,Spring,我有一张表格: <form method="post" action="/addExpense"> <input type="text" name="description" required> <input type="number" name="amount" required> <input type="date" name="created" required> <input type="date" name="updated" re
<form method="post" action="/addExpense">
<input type="text" name="description" required>
<input type="number" name="amount" required>
<input type="date" name="created" required>
<input type="date" name="updated" required>
<input type="submit">
</form>
费用明细到目录:
public class ExpenseDetailDTO {
String description;
Long amount;
Date created;
Date updated;
...
}
当我提交表格时,我的请求是错误的。在chrome dev工具中检查表单数据时,会显示:
description:description
amount:500
created:2016-01-01
updated:2016-01-01
我认为Spring无法从java.util.Date中的表单转换日期
如何将日期传递给控制器
编辑:
添加了DateTimeFormat的注释:
public class ExpenseDetailDTO {
String description;
Long amount;
@DateTimeFormat(pattern = "yyyy-MM-dd")
Date created;
@DateTimeFormat(pattern = "yyyy-MM-dd")
Date updated;
....
}
仍然给出了400个错误请求。您应该使用Spring DateTimeAnnotation格式化日期。使用以下注释 创建日期 @DateTimeFormat(pattern=“yyyy-MM-dd”)日期已更新
在ExpenseDetailDTO类上,使用controller中的initbinder方法从jsp绑定日期值
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}