经过一天的研究,我发现Spring读取了Web请求中发送的值,并尝试将其与Filter对象绑定。
对于日期值,它会查找具有“MM/dd/yyyy”格式的值。如果您发送具有其他格式的值,则它不起作用。
要解决这个问题,可以使用注解“InitBinder”。
@InitBinder
private 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);
}
这个方法针对每个网络请求执行。在这里,我调用我的“dateFormat()”方法来获取用户偏好中的格式,并向 Spring 说它在 Web 请求中找到的所有 java.util.Date 都具有这种格式。
这是我的完整代码:
过滤器:
import java.util.Date;
@lombok.Data
public 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();
}
@InitBinder
private 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 class="row">
<div class="col-xs-12 col-sm-6">
<div class="input-group date">
<input type="date" th:type="date" class="form-control"
th:id="loadingStartDate" th:name="loadingStartDate"
th:value="${#dates.format(filter.loadingStartDate, dateFormat)}" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-xs-12 col-sm-12">
<button type="submit" class="btn btn-primary btn-lg pull-right">
submit
</button>
</div>
</div>
</div>
</form>