views:

849

answers:

1

I'm getting blocked on a jsp page and our 1 java engineer isn't able to help now.

There is a template called "module-review.jsp" that is loaded in 2 instances, via a normal page load an via an api that returns it as part of a json object.

There is a variable called "review.updatedDate". On a normal page view, this variable is loaded as a hashmap into the page and looks like this:

{_value=2009-07-02 11:54:30.0, class=sql-timestamp}

So if I want the date value, I use ${review.updatedDate._value}

However, when module-review.jsp is loaded by the API, the date value is returned directly as a date object, where ${review.updatedDate} returns the date value directly.

I need to have a set of conditional statements that will only display ${review.updatedDate} if ._value doesn't exist. Everything I have tried gives me errors that ._value doesn't exist, which is rather ironic.

I am currently trying to use this, but it fails on the 2nd conditional:

<c:if test="${ (not empty review.updatedDate['_value']) }">
${review.updatedDate._value}
</c:if>

<c:if test="${ (empty review.updatedDate['_value']) }">
${review.updatedDate}
</c:if>
+1  A: 

Apart from "don't do it that way", I guess you could test the type of updatedDate:

<c:choose>
    <c:when test="${review.updatedDate.class.name == 'java.util.Date'}">
     Date: ${review.updatedDate}
    </c:when>
    <c:otherwise>
     Map: ${review.updatedDate._value}
    </c:otherwise>
</c:choose>

...assuming that the date is an instance of the Date class. Strangely, this approach didn't work when I tried to test for java.util.HashMap.


Perhaps a more reliable approach would be to hand the test off to a Java class:

package typetest;

import java.util.Map;

public class TypeUtil {

    public static boolean isMap(Object o) {
     return o instanceof Map;
    }

}

This can be mapped to a custom function via a TLD file (e.g. WEB-INF/maptest.tld):

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
    version="2.1">
    <tlib-version>1.0</tlib-version>
    <short-name>myfn</short-name>
    <uri>http://typeutil&lt;/uri&gt;
    <function>
     <name>isMap</name>
     <function-class>typetest.TypeUtil</function-class>
     <function-signature>boolean isMap(java.lang.Object)</function-signature>
    </function>
</taglib>

Sample JSP that imports the function:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%&gt;
<%@ taglib prefix="myfn" uri="http://typeutil"%&gt;
<html>
<body>
<c:choose>
    <c:when test="${myfn:isMap(review.updatedDate)}">
     Map: ${review.updatedDate._value}
    </c:when>
    <c:otherwise>
     Date: ${review.updatedDate}
    </c:otherwise>
</c:choose>
</body>
</html>
McDowell