gpt4 book ai didi

java - 在spring mvc应用中提交输入类型="date"

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:32 25 4
gpt4 key购买 nike

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

到目前为止我的代码:

后台.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";
}

最佳答案

您必须在 Controller 中使用@InitBinder 才能直接绑定(bind)日期:

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);
}

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

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

关于java - 在spring mvc应用中提交输入类型="date",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com