如何在Spring MVC 3.0中显示格式化的DateTime?


问题内容

我的模型中有一个Joda-DateTime字段,并希望以JSP视图的格式显示它。我已经用新的@DateTimeFormat注释对其进行了注释:

public class Customer {
   private DateTime dateOfBirth;

   @DateTimeFormat(style="M-")
   public DateTime getDateOfBirth() {
      return dateOfBirth;
   }
}

现在,我想在我的JSP中显示dateOfBirth:

Date of birth: ${customer.dateOfBirth}

但是结果是未格式化的:

Date of birth: 2010-08-11T11:23:30.148+02:00

经过一番研究,我发现我必须使用spring:bind-tag:

<spring:bind path="customer.dateOfBirth">
   Date of birth: ${status.value}
</spring:bind>

这样就可以了。但是对于这个简单的任务来说似乎太复杂了。由于必须将list-index集成到绑定路径中,因此在列表上使用此方法更加复杂。

所以我的问题是:是否有一种使用spring格式注释显示格式值的更简单方法?


问题答案:

使用spring:eval了解@DateTimeFormat规则的标签:

<spring:eval expression="customer.dateOfBirth" />

另外,您可以@DateTimeFormat从模型中完全删除规则,并使用Joda的formatDate标签,如Naikus所示。

在将来的发行版中,Spring计划支持插入“ SpEL”(这是spring:eval调用的“ Spring表达式语言”),作为JSP页面的默认Unified
EL实现。这将允许内联表达式 ${customer.dateOfBirth}也可以通过SpEL进行路由。您可以在以下位置对此增强请求投票: https
//jira.spring.io/browse/SPR-7459