Spring MVC: how to display formatted date values in JSP EL

Brice Roncace picture Brice Roncace · Dec 17, 2014 · Viewed 23.3k times · Source

Here's a simple value bean annotated with Spring's new (as of 3.0) convenience @DateTimeFormat annotation (which as I understand replaces the pre-3.0 need for custom PropertyEditors as per this SO question):

import java.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;

public class Widget {
  private String name;

  @DateTimeFormat(pattern = "MM/dd/yyyy")
  private LocalDate created;

  // getters/setters excluded
}

When biding the values from a form submission to this widget, the date format works flawlessly. That is, only date strings in the MM/dd/yyyy format will convert successfully to actual LocalDate objects. Great, we're halfway there.

However, I would also like to be able to also display the created LocalDate property in a JSP view in the same MM/dd/yyyy format using JSP EL like so (assuming my spring controller added a widget attribute to the model):

${widget.created}

Unfortunately, this will only display the default toString format of LocalDate (in yyyy-MM-dd format). I understand that if I use spring's form tags the date displays as desired:

<form:form commandName="widget">
  Widget created: <form:input path="created"/>
</form:form>

But I'd like to simply display the formatted date string without using the spring form tags. Or even JSTL's fmt:formatDate tag.

Coming from Struts2, the HttpServletRequest was wrapped in a StrutsRequestWrapper which enabled EL expressions like this to actually interrogate the OGNL value stack. So I'm wondering if spring provide something similar to this for allowing converters to execute?

EDIT

I also realize that when using spring's eval tag the date will display according the pattern defined in the @DateTimeFormat annotation:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="widget.created"/>

Interestingly, when using a custom PropertyEditor to format the date, this tag does NOT invoke that PropertyEditor's getAsText method and therefore defaults to the DateFormat.SHORT as described in the docs. In any event, I'd still like to know if there is a way to achieve the date formatting without having to use a tag--only using standard JSP EL.

Answer

Eduardo Mioto picture Eduardo Mioto · Mar 11, 2015

You may use the tag to provide you these kind of formattings, such as money, data, time, and many others.

You may add on you JSP the reference: <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

And use the formatting as: <fmt:formatDate pattern="yyyy-MM-dd" value="${now}" />

Follows below a reference:

http://www.tutorialspoint.com/jsp/jstl_format_formatdate_tag.htm