I've created a basic input form with a number of strings using Spring Web application in Intellij. The form successfully saves to the backend when using strings only so I decided to add a date field in the model and tried to modify to controller/jsp to accept this in the input form (and display in the record list). I'm having problems with the input form not getting the value.
Entity:
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern="dd.MM.yyyy")
private Date dueDate;
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
JSP (I assume value should be blank here as I am starting with an empty field to fill in?):
Due Date:
"/>
Controller:
@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/";
}
My debug shows Due Date:null so nothing is being send for my date field from the form when posted. This means that the date field is never saved then the repository save occurs.
解决方案
You have to register an InitBinder in your controller to let spring convert your date string to java.util.Date object and set it in command object. Include following in your controller :
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
Modify your jsp with :
"/>