jspstruts2eljava-timevaluestack

Using Java8 time in JSPs


For my open source project I'm in the process of switching date fields from java.util.Date to Java 8's java.time.LocalDateTime.

In the JSP's I'm using Struts tags to format the java.util.Date from the passed-in bean, however, those won't work with Java 8 time. I use the Struts tag not only to retrieve the time field but also the formatting string to be used to parse it:

<s:text name="generic.date.toStringFormat">
    <s:param value="myBean.timeField" />
</s:text>

"generic.date.toStringFormat" is in the message resource file, and myBean.timeField is from the Action form backing the JSP.

Looking at this post: JSTL LocalDateTime format, it seems there are two alternatives I can use, Sargue's https://github.com/sargue/java-time-jsptags or a custom EL function, for example with the former:

<javatime:format value="myBean.timeField" pattern="generic.date.toStringFormat"/>

Problem is, "myBean.timeField" and "generic.date.toStringFormat" seem to be resolvable only within Struts tags. If <javatime> were a standard HTML tag, I could use <s:property/> to get the values resolved, e.g.,

<span><s:property value="myBean.timeField"/></span>

But <javatime:.../> is a JSP tag and I can't seem to resolve Struts JSP tags within other JSP tags. Question: How can I extract the bean value myBean.timeField and the message resource value generic.date.toStringFormat into variables so I can reference them in the <javatime/> tag above? (If this can be done via the custom EL function option instead, that will work for me also.)


Solution

  • You can use EL in the value attribute. Struts2 wrapped a request to search attributes from the valueStack. This is native access to your action variables from the EL.

    <javatime:parseLocalDateTime value="${myBean.timeField}" pattern="generic.date.toStringFormat" var="parsedDate" />