8

I am using JSPs for the view, and Spring MVC 3.0 for the controller. In my JSP, I want to show the current DateTime, for which I have the following code...

<c:set var="dateTimeDisplayFormat" value='<spring:message code="display.dateFormat" />'/>

<c:set var="currentDateTime" 
    value='<%= new SimpleDateFormat(${dateTimeDisplayFormat}).format(new Date()) %>' 
    scope="page" />

Now, the problem is JSTL fails to recognize my nested tag for SimpleDateFormat instantiation. I wish to pass the format string (As obtained from the 'dateTimeDisplayFormat' variable) to the SimpleDateFormat constructor.

Can someone please advice how do I write the nested constructor for SimpleDateFormat in the c:set statement above?

Thanks in anticipation!

Yannick Huber
  • 607
  • 2
  • 16
  • 35
PaiS
  • 1,282
  • 5
  • 16
  • 23

1 Answers1

16

<c:set> can take its value from the tag content, instead of from the value attribute:

<c:set var="dateTimeDisplayFormat">
    <spring:message code="display.dateFormat" />
</c:set>

<c:set var="currentDateTime" scope="page">
    <%= new SimpleDateFormat(${dateTimeDisplayFormat}).format(new Date()) %>
</c:set>    

Better yet, you shouldn't need <c:set> at all, since both <spring:message> and <fmt:formatDate> can store their results in variables for you:

<spring:message code="display.dateFormat" var="dateTimeDisplayFormat"/>
<fmt:formatDate pattern="${dateTimeDisplayFormat}" var="currentDateTime" scope="page"/>
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Thank you so much Skaffman, but the first solution that you proposed, did not work :(. It gives me an exception
    PWC6197: An error occurred at line: 27 in the jsp file: /WEB-INF/views/common/header.jsp PWC6199: Generated servlet error: Syntax error on token "$", AssignmentOperator expected after this token Thanks for opening my eyes to the 2nd approach, but with that, the date does now show up on the page, with all my remaining code being the same ie.
    – PaiS Jul 28 '10 at 08:44
  • OMG! So dumb of me, I had not included the format JSTL library at the top of the page, and hence the 2nd approach wasn't working. Now it shows up date perfectly, and thank you so much Skaffman for the neat approach! – PaiS Jul 28 '10 at 09:01
  • 1
    the answer is correct in it's spirit, but the syntax error is comes from mixing scriptlets with el. This is literal java code (argh, shouldn't happen in a JSP), so the el variable can (but shouldn't) be accessed like this: `<%= new SimpleDateFormat(pageContext.getAttribute("dateTimeDisplayFormat")).format(new Date()) %>` – Sean Patrick Floyd Jul 28 '10 at 09:04
  • I agree that literal java code is a mess, but when it was necessary for me, so thank you. – Adam Oct 28 '10 at 18:11