kay*_*pim 4 spring jsp tomcat intellij-idea
我使用Intellij中的Spring Web应用程序创建了一个包含许多字符串的基本输入表单.当只使用字符串时,表单成功保存到后端,所以我决定在模型中添加一个日期字段,并尝试修改为controller/jsp以在输入表单中接受它(并显示在记录列表中).我遇到输入表单没有获得值的问题.
实体:
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern="dd.MM.yyyy")
private Date dueDate;
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
Run Code Online (Sandbox Code Playgroud)
JSP(我假设值应为空白,因为我从一个空字段开始填写?):
<div class="control-group">
<form:label cssClass="control-label" path="dueDate">Due Date:</form:label>
<div class="controls">
<input type="text" path="dueDate" class= "date" name = "dueDate" value = "<fmt:formatDate value="" pattern="MM-dd-yyyy" />"/>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
@RequestMapping(value = "/todos/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute("todo") Todo todo, BindingResult result) {
System.err.println("Title:"+todo.getTitle());
System.err.println("Due Date:"+todo.getDueDate());
todoRepository.save(todo);
return "redirect:/todos/";
}
Run Code Online (Sandbox Code Playgroud)
我的调试显示截止日期:null,因此发布时表单中的日期字段没有发送任何内容.这意味着永远不会保存日期字段,然后发生存储库保存.
Ris*_*asu 11
您必须在控制器中注册一个InitBinder,以便将日期字符串转换为java.util.Date对象并将其设置在命令对象中.在您的控制器中包含以下内容:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
Run Code Online (Sandbox Code Playgroud)
修改你的jsp:
<input type="text" path="dueDate" class= "date" name = "dueDate" value = "<fmt:formatDate value="${cForm.dueDate}" pattern="MM-dd-yyyy" />"/>
Run Code Online (Sandbox Code Playgroud)