JSP form date input field
Solution 1
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 :
<input type="text" path="dueDate" class= "date" name = "dueDate" value = "<fmt:formatDate value="${cForm.dueDate}" pattern="MM-dd-yyyy" />"/>
Solution 2
In your model class use the annotation provided by DateTimeFormat by spring
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@DateTimeFormat(pattern = "MM-dd-yyyy")
private Date birthdate;
In your jsp the date will bind automatically without error
<form:input path="birthdate" cssClass="form-control" />
Note: date format must be dd-mm-yy i.e. 27-10-2017 if you use other format it will cause exception
Solution 3
try using spring input like:
<div class="control-group">
<form:label cssClass="control-label" path="dueDate">Due Date:</form:label>
<div class="controls">
<form:input path="dueDate" class="date" />
</div>
</div>
and in dueDate
input you have:
value="<fmt:formatDate value="" pattern="MM-dd-yyyy" />"
this is unused, you have not provided value at all.
kayakpim
Updated on January 21, 2020Comments
-
kayakpim over 4 years
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?):
<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>
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.