经过一天的研究,我发现Spring读取了Web请求中发送的值,并尝试将其与Filter对象绑定。
对于日期值,除了找到格式为“ MM / dd / yyyy”的值外。如果您以其他格式发送值,则该值不起作用。
要解决此问题,可以使用注释“ InitBinder”。
@InitBinderprivate void dateBinder(WebDataBinder binder) { //The date format to parse or output your dates SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat()); //Create a new CustomDateEditor CustomDateEditor editor = new CustomDateEditor(dateFormat, true); //Register it as custom editor for the Date type binder.registerCustomEditor(Date.class, editor);}针对每个Web请求执行此方法。在这里,我调用“
dateFormat()”方法来获取用户首选项中的格式,并告诉Spring它在Web请求中找到的所有java.util.Date都具有这种格式。
这是我的完整代码:
筛选器:
import java.util.Date;@lombok.Datapublic class TestDateFilter { private Date myDate; public TestDateFilter() { this.myDate = new Date(); }}控制器:
@RequestMapping(value = "/testdate")public String testDate(Model model) { model.addAttribute("filter", new TestDateFilter()); return "testdate";}@RequestMapping(value = "/testdate", method = RequestMethod.POST)public String testDatePost(@ModelAttribute("filter") TestDateFilter filter, Model model) { System.out.printf(filter.getLoadingStartDate().toString()); System.out.printf(dateFormat()); return "testdate";}@ModelAttribute("dateFormat")public String dateFormat() { return userPreferenceService.getDateFormat();}@InitBinderprivate void dateBinder(WebDataBinder binder) { //The date format to parse or output your dates SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormat()); //Create a new CustomDateEditor CustomDateEditor editor = new CustomDateEditor(dateFormat, true); //Register it as custom editor for the Date type binder.registerCustomEditor(Date.class, editor);}HTML:
<form th:action="@{/testdate}" th:object="${filter}" th:method="POST"> <div > <div > <div > <input type="date" th:type="date" th:id="loadingStartDate" th:name="loadingStartDate" th:value="${#dates.format(filter.loadingStartDate, dateFormat)}" /> </div> </div> </div> <div > <div > <div > <button type="submit" > submit </button> </div> </div> </div> </form>


