JSTL: check for property

I am blocked on the jsp page and our 1 java engineer is now unable to help.

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

There is a variable called "review.updatedDate". In a normal pageview, this variable is loaded as a hash map on the page and looks like this:

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

So, if I need a 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 does not exist. Everything I tried gives me errors that ._value does not exist, which is pretty ironic.

I am currently trying to use this, but it does not work in the second conditional expression:

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

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

Besides the “don't do it this way”, I think you can check for updateDate type:

<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 the date is an instance of the Date class . Oddly enough, this approach did not work when I tried to check java.util.HashMap.


Perhaps a more robust approach is to pass a test to the Java class:

package typetest;

import java.util.Map;

public class TypeUtil {

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

}

TLD (, 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</uri>
    <function>
        <name>isMap</name>
        <function-class>typetest.TypeUtil</function-class>
        <function-signature>boolean isMap(java.lang.Object)</function-signature>
    </function>
</taglib>

JSP, :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="myfn" uri="http://typeutil"%>
<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>
+4

Source: https://habr.com/ru/post/1711760/


All Articles