【问题标题】:Submit input type="date" in spring mvc application在 spring mvc 应用程序中提交 input type="date"
【发布时间】:2017-05-04 14:56:36
【问题描述】:

我想向 spring mvc 控制器提交“日期”类型的输入。 不幸的是,我不断收到很多错误。我是 spring mvc 的新手,尤其是表单提交,我不太清楚为什么我需要在表单中包含“commandName”。

到目前为止我的代码:

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>

控制器:

@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";
}

【问题讨论】:

  • 只使用 RequestParam 而不是 ModelAttribute
  • @Rajesh 我认为需要基于“View API”的解决方案(JSTL + 模型)

标签: java spring forms date spring-mvc


【解决方案1】:

你必须在你的控制器中使用@InitBinder 来直接绑定日期:

Spring 自动绑定简单数据(Strings、int、float 等) 进入命令 bean 的属性。然而,当 数据更复杂,例如,当您想要 以“Jan 20, 1990”格式捕获一个字符串并让 Spring 创建一个 日期对象从它作为绑定操作的一部分。对于这项工作, 您需要通知 Spring Web MVC 使用 PropertyEditor 实例作为 绑定过程的一部分:

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

现在您可以直接在您的方法中获取解析后的日期,格式为 "MMM d, YYYY" :

@RequestMapping(value = "/getAllOnDate", method = RequestMethod.POST)
public String getAllReservationsForRestaurantOnDate(@ModelAttribute("date") Date date, Model model) {
   LOG.info(date.toString());
   return "anotherPage";
}

【讨论】:

  • 大写 YYYY 是“week year”,小写“yyyy”是日历年 - 我想你想要那个
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 2016-01-13
  • 2012-03-30
  • 2011-09-06
  • 2016-01-23
  • 2013-05-29
相关资源
最近更新 更多