Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSP form date input field

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.

like image 715
kayakpim Avatar asked Apr 01 '14 13:04

kayakpim


2 Answers

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" />"/>
like image 195
Rishav Basu Avatar answered Sep 28 '22 14:09

Rishav Basu


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

like image 36
Dipen Avatar answered Sep 28 '22 14:09

Dipen