最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - if else in jstl tags within jsp page - Stack Overflow

programmeradmin5浏览0评论
<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.
Share Improve this question asked Feb 28, 2013 at 9:59 RachelRachel 1,15911 gold badges26 silver badges43 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

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'}
发布评论

评论列表(0)

  1. 暂无评论