4

I want to submit an input of type "date" to a spring mvc Controller. Unfortunately, I keep getting numerous errors. I'm new to spring mvc and especially to form submitting, not very clear to me why I need to have "commandName" in form.

My code so far:

backoffice.jsp:

<form:form method="POST" action="/getAllOnDate" commandName="date">
<table>
    <td><form:label path="date">Date</form:label></td>
    <td><form:input type="date" path="date"/></td>
    <input type="submit" value="View all on date"/>
</table>
</form:form>

Controller:

@RequestMapping(value = "/backoffice", method = RequestMethod.GET)
public String backofficeHome(Model model) {
    model.addAttribute("date", new Date());

    return "backoffice";
}

@RequestMapping(value = "/getAllOnDate", method = RequestMethod.POST)
public String getAllReservationsForRestaurantOnDate(@ModelAttribute("date") Date date, Model model) {
   LOG.info(date.toString());
   return "anotherPage";
}
2
  • just use RequestParam instead of ModelAttribute Commented May 4, 2017 at 15:14
  • @Rajesh I think "View API"-based solution (JSTL + Model) is requested Commented May 5, 2017 at 8:53

1 Answer 1

3

You have to use @InitBinder in your controller ot bind the date directly :

Spring automatically binds simple data (Strings, int, float, etc.) into properties of your command bean. However, what happens when the data is more complex for example, what happens when you want to capture a String in “Jan 20, 1990” format and have Spring create a Date object from it as part of the binding operation. For this work, you need to inform Spring Web MVC to use PropertyEditor instances as part of the binding process :

@InitBinder
public void bindingPreparation(WebDataBinder binder) {
  DateFormat dateFormat = new SimpleDateFormat("MMM d, YYYY");
  CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true);
  binder.registerCustomEditor(Date.class, orderDateEditor);
}

Now you can get the parsed date directly in your method formated as "MMM d, YYYY" :

@RequestMapping(value = "/getAllOnDate", method = RequestMethod.POST)
public String getAllReservationsForRestaurantOnDate(@ModelAttribute("date") Date date, Model model) {
   LOG.info(date.toString());
   return "anotherPage";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Upper case YYYY is "week year", lowercase "yyyy" is calendar year - I think you want that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.