我正在Spring MVC中构建一个项目,我想为用户添加一个日期选择器,但是提交的日期始终是错误的。
示例输入-2018年12月6日
我得到的输出-'Wed Feb 12 00:00:00 EET 195','Sat Feb 12 00:00:00 EET 169'
<form:form method="POST" modelAttribute="${AttributeNames.DATE}">
<table align="center" >
<tr>
<td><label>Date</label></td>
<td>
<form:input type="date" path="date"/>
</td>
</tr>
</table>
</form:form>
控制器:
@InitBinder
public void bindingPreparation(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-
yyyy");
CustomDateEditor orderDateEditor = new
CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, orderDateEditor);
}
//localhost:8080/project/deadline
@GetMapping(Mappings.DEADLINE)
public String getDeadline(Model model){
log.info("getDeadline called");
DateModel dateModel = new DateModel();
model.addAttribute(AttributeNames.DATE, dateModel);
return ViewNames.DEADLINE;
}
@PostMapping(Mappings.DEADLINE)
public String postDeadLine(@ModelAttribute(AttributeNames.DATE) DateModel dateModel) {
log.info("postDeadline called with date = {}", dateModel.getDate().toString());
bookService.setDeadLine(bookId, dateModel.getDate());
return "redirect:/" + Mappings.BOOKS;
}
DateModel:
@Data
public class DateModel {
@DateTimeFormat(pattern = "MM-dd-yyyy")
private Date date;
public DateModel(Date date) {
this.date = date;
}
public DateModel(){
this(null);
}
}
Constants :
Mappings.DEADLINE = "deadline"
ViewNames.DEADLINE = "deadline"
AttributeNames.DATE = "dateModel"