2017-05-04 33 views
2

我想向spring mvc控制器提交一個類型爲「date」的輸入。 不幸的是,我不斷收到許多錯誤。我是新的春天mvc,特別是形式提交,不是很清楚爲什麼我需要在表單中有「commandName」。在spring mvc應用程序中提交input type =「date」

我迄今爲止代碼:

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"; 
} 
+0

只使用RequestParam代替的ModelAttribute – Rajesh

+0

@Rajesh我覺得 「查看API」 爲基礎的解決方案(JSTL +模型)請求 – LoganMzz

回答

0

你必須使用@InitBinder在控制器OT日期直接綁定:

Spring自動綁定簡單的數據一個(字符串,int,float等) 到你的命令bean的屬性中。但是,如果 數據更復雜,會發生什麼情況,例如,當您想要 以「1990年1月20日」格式捕獲字符串並讓Spring從其創建Date對象作爲綁定操作的一部分時發生了什麼。對於這項工作, 您需要通知的Spring Web MVC使用屬性編輯器實例作爲綁定過程的 部分:

@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"; 
} 
相關問題