如何在 Spring MVC 3.0 中显示格式化的 DateTime? [英] How to display a formatted DateTime in Spring MVC 3.0?

查看:35
本文介绍了如何在 Spring MVC 3.0 中显示格式化的 DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Joda-DateTime field in my model and want to display it formatted in a JSP view. I have annotated it with the new @DateTimeFormat annotation:

public class Customer {
   private DateTime dateOfBirth;

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

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

Now I want to display the dateOfBirth in my JSP:

Date of birth: ${customer.dateOfBirth}

但是结果是未格式化的:

But the result is unformatted:

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

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

After some research I found out, that I have to use the spring:bind-tag:

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

有了这个就可以了.但是对于这个简单的任务来说似乎太复杂了.而且在列表上使用这种方法更加复杂,因为您必须将列表索引集成到绑定路径中.

With this it works. But it seems too complicated for this simple task. And using this method on lists is even more complicated since you have to integrate the list-index into the binding-path.

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

So my question is: Is there a simpler way to display a formatted value using the spring formatting-annotations?

推荐答案

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

Use the spring:eval tag which understands the @DateTimeFormat rule:

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

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

Alternatively, you can remove the @DateTimeFormat rule from your model all-together and use Joda's formatDate tag as Naikus illustrates.

在未来的版本中,Spring 计划支持插入SpEL",这是 spring:eval 调用的Spring 表达式语言",作为 JSP 页面的默认统一 EL 实现.这将允许像 ${customer.dateOfBirth} 这样的内联表达式也可以通过 SpEL 进行路由.您可以在此处投票支持此增强请求:https://jira.spring.io/browse/SPR-7459.

In a future release, Spring plans to support plugging in "SpEL", which is the "Spring Expression Language" invoked by spring:eval, as the default Unified EL implementation for your JSP pages. This would allow in-line expressions like ${customer.dateOfBirth} to be routed through SpEL as well. You can vote up this enhancement request here: https://jira.spring.io/browse/SPR-7459.

这篇关于如何在 Spring MVC 3.0 中显示格式化的 DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆