<div align="right">
<b> Connected:</b> <%=(String)session.getAttribute("CONNECTION_DBNAME")%>
</div>
- I have the above code in jsp page
- Initially the the session CONNECTION_DBNAME has no value.
- When CONNECTION_DBNAME is null, i need to display not connected
- When CONNECTION_DBNAME has value, the some value gets printed.
- I know it can be achieved by using if else with condition, but i don't know how to use if else within jstl tag.
<div align="right">
<b> Connected:</b> <%=(String)session.getAttribute("CONNECTION_DBNAME")%>
</div>
- I have the above code in jsp page
- Initially the the session CONNECTION_DBNAME has no value.
- When CONNECTION_DBNAME is null, i need to display not connected
- When CONNECTION_DBNAME has value, the some value gets printed.
- I know it can be achieved by using if else with condition, but i don't know how to use if else within jstl tag.
- numerous duplicates that provide the answer :stackoverflow./questions/4587397/… and stackoverflow./questions/6219267/if-else-in-jstl – olly_uk Commented Feb 28, 2013 at 10:05
3 Answers
Reset to default 5<c:if test="${sessionScope.CONNECTION_DBNAME!= null}">
Connected:${sessionScope.CONNECTION_DBNAME}
</c:if>
<c:if test="${sessionScope.CONNECTION_DBNAME== null}">
NOT CONNECTED
</c:if>
or
<c:choose>
<c:when test="${sessionScope.CONNECTION_DBNAME != null}">
Connected:${sessionScope.CONNECTION_DBNAME}
</c:when>
<c:otherwise>
NOT CONNECTED
</c:otherwise>
</c:choose>
<div align="right">
<b> Connected:</b> <%=(session.getAttribute("CONNECTION_DBNAME")!=null)?(String)session.getAttribute("CONNECTION_DBNAME"): "not connected"%>
</div>
You can do the same thing as @PSR remended, just written a bit smaller, using a ternary expression, like this:
${empty sessionScope.CONNECTION_DBNAME ? 'NOT CONNECTED' : 'Connected' + sessionScope.CONNECTION_DBNAME }
or the reverse; check not empty
and swap the position of the two results..
${not empty sessionScope.CONNECTION_DBNAME ? 'Connected' + sessionScope.CONNECTION_DBNAME : 'NOT CONNECTED'}