栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

提交Spring表单时日期格式错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

提交Spring表单时日期格式错误

经过一天的研究,我发现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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号