Search code examples
jspjstl

How to check null in JSTL <c:out> tag?


I'm looking for a possibility to either insert a variable in a table cell or if the value turns out to be null, write another text in the cell, but with different styling. How can I achieve that?

this one obviously doesnt work:

<c:out value="${data.onlineData.state}" default="<span class="customercare-null"><spring:theme code="productOffline.null" /></span>" escapeXml="false" />

would this be correct syntax for what I'm trying to achieve?

<c:out value="${data.onlineData.state}">
    <span class="customercare-null"><spring:theme code="productOffline.null" /></span>
</c:out>

i know that a c:choose could solve this, but i'd rather like to know if the code presented above is also legit

thank you in advance


Solution

  • Use <c:if> to check null value

    <c:if test="${empty data.onlineData.state}">
        <span class="customercare-null"><spring:theme code="productOffline.null" /></span>
    </c:if>
    <c:if test="${not empty data.onlineData.state}">
       <c:out value="${data.onlineData.state}" />
    </c:if>
    

    Or using <c:choose>:

    <c:choose>
        <c:when test="${empty data.onlineData.state}">
            <span class="customercare-null"><spring:theme code="productOffline.null" /></span>
        </c:when>
        <c:otherwise>
           <c:out value="${data.onlineData.state}" />
        </c:otherwise>
    </c:choose>
    

    would this be correct syntax for what I'm trying to achieve?

    If you use

    <c:out value="${data.onlineData.state}">
        <span class="customercare-null"><spring:theme code="productOffline.null" /></span>
    </c:out>
    

    Then <span class="customercare-null"><spring:theme code="productOffline.null" /></span> will diplay as text. Html component will not render.