tags:

views:

270

answers:

2

I'm writing a JSP that sometimes needs to format a Java Date that comes out of the request. I'm doing it like this:

<fmt:formatDate value="${attribute.value}" pattern="yyyy-MM-dd HH:mm:ss"/>

and it works beautifully on Java Dates.

However, there are times that the request attribute field with the exact same name (attribute.value) is not actually a date and should not be formatted as such. What I would like to do is simply pass that string through the fmt:format tag as-is, rather than throwing an exception on an unparseable date.

I could accomplish something similar using a c:choose but I'd rather separate the JSP view from the underlying data as much as possible, so this isn't the ideal choice for me. So, is there a way to make something like

<fmt:formatDate value="I AM NOT A DATE" pattern="yyyy-MM-dd HH:mm:ss"/>

evaluate to, simply,

I AM NOT A DATE

in the generated HTML?

A: 

Make a tag :-) That way you can define the c:choose in your tag file, and in your JSPs just have a single clean line that is almost identical to what you have, eg.:

<your:formatDate value="I AM NOT A DATE" pattern="yyyy-MM-dd HH:mm:ss"/>

(Or if you always use the same pattern, you could even hard-code it in to your tag and make the above even cleaner.)

Comment back if you have questions on custom tags.

EDIT: Here's how you could make a tag for this, if you ever want to try:

1) Make a "WEB-INF/tags/someNamespace/yourTag.tag", with the following code:

<%@ tag isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ attribute name="date" type="java.util.Date" required="true" %>
<c:choose>
<c:when test="${date instanceOf java.util.Date}">
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd HH:mm:ss"/>
</c:when>
<c:otherwise>${date}</c:otherwise>
</c:choose>

2) Add the tag to your page:

<%@ taglib tagdir="/WEB-INF/tags/someNamespace" prefix="s" %>

3) Use it:

<s:yourTag date="${attribute.date}"/>

As you can see, it really doesn't take that much code, and if you do wind up repeating this logic elsewhere you'll find custom tags very handy.

machineghost
I have no experience making my own tags, but I think that's probably overkill for my application. At least right now, there's only 1 place in 1 JSP that I would need this. Sure, there could be a use for it in the future, but right now, this is making more code, not less.
Matt Ball
Following up: I'm not actually sure of how I'd write the choose for this. Is there a try/catch-like tag I could use? A way to test if something is a Date should be sufficient, as well.
Matt Ball
A: 

This was simple enough to do:

<c:catch var="ex">
    <fmt:formatDate value="${attribute.value}" pattern="yyyy-MM-dd HH:mm:ss"/>
</c:catch>
<c:if test="${not empty ex}">
    ${attribute.value}
</c:if>

Not as elegant as I was hoping for, but it works.

Matt Ball