【问题标题】:is there a way to more elegantly manipulate Date objects in this example?在这个例子中,有没有办法更优雅地操作 Date 对象?
【发布时间】:2012-04-14 09:12:00
【问题描述】:

我有这个问题,我要求用户输入我使用 JQueryUI 的日期,将其格式化为 MM/dd/yyyy 字符串。但是,我的表单对象接受日期,所以我希望能够通过表单将此字符串作为日期发送。

<input type="text" class="points datepicker" name="evaluationYear2"
                           value="${nomination.evaluationYear2}"
                           <c:if test="${mode==cons.READ_ONLY}">disabled</c:if> />

我需要将evaluationYear2 作为日期对象(而不是字符串)发送。我怎样才能做到这一点?此外,nomination 是一个 form 对象,由于我的控制器方法,我正在接收它并且只是为了查看(即当出现错误时,它会用以前的信息刷新),显然这会将它发回作为日期对象,我也需要将其格式化为 MM/dd/yyyy。

我试过这个没有用,显然是因为它在编码方面没有任何意义:

<input type="text" class="points datepicker" name="evaluationYear2t"
                           value="${nomination.evaluationYear2}"
                           <c:if test="${mode==cons.READ_ONLY}">disabled</c:if> />

 <fmt:parseDate var="evaluationYear2" value="${evaluationYear2t}" type="DATE" pattern="MM/dd/yyyy"/>

【问题讨论】:

  • 日期解析应该在控制器端进行。 IE。在 Spring MVC 方面。
  • 所以我应该将日期作为字符串发送?但是我不能像在我的表单中使用@Past 注释那样进行验证,因为我的提交方法接受@Valid form object。 @Past 是否可以与字符串一起使用?我显然是新手,对不起。我想说的是,它必须在提交和控制器方法之间完成才能被验证。也许使用javascript?
  • 我通读了static.springsource.org/spring/docs/current/… 我在我的应用程序中使用的解决方案是实现一个转换器并使用转换器和转换注释在字符串和日期时间之间自动来回转换。根据文档,看起来可能有更好的方法来做到这一点。

标签: java spring jakarta-ee spring-mvc jstl


【解决方案1】:

最好将日期发送为字符串,甚至时间戳。 你可以在这里使用@InitBinder

@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

或者,您可以使用HttpServletRequest对象中的getParameter()直接从请求中获取参数并手动进行验证。

【讨论】:

    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2021-12-14
    • 2011-03-04
    相关资源
    最近更新 更多