首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JSP EL 表達式判斷 sessionScope 變數是否為空

     編輯:程式設計綜合問答

JSP EL 表達式正確判斷 sessionScope 變數空值

在 JSP 中使用 EL 表達式 ${sessionScope.uNames} 時,常需判斷變數是否存在或為空。直接使用 if (xx != null) 或 xx.equals("") 在 EL 中無法正常運作。

正確寫法:使用 empty 運算子

<c:if test="${!empty sessionScope.uNames}">
    <!-- uNames 有值且非空 -->
    歡迎,${sessionScope.uNames}!
</c:if>

<c:if test="${empty sessionScope.uNames}">
    <!-- uNames 為 null、空字串、空集合、空陣列 -->
    請先登入
</c:if>

empty 運算子判斷邏輯

empty 運算子會回傳 true 的情況:

  • 值為 null
  • 空字串 ""
  • 空陣列 new String[0]
  • 空集合 Collections.EMPTY_LIST
  • 空 Map Collections.EMPTY_MAP

常見錯誤寫法

<!-- 錯誤:EL 不支援 != 運算子 -->
<c:if test="${sessionScope.uNames != null}">...</c:if>

<!-- 錯誤:equals 方法在 EL 中無法直接呼叫 -->
<c:if test="${sessionScope.uNames.equals('')}">...</c:if>

<!-- 錯誤:空字串比較語法錯誤 -->
<c:if test="${sessionScope.uNames == ''}">...</c:if>

進階判斷:區分 null 與空字串

<c:choose>
    <c:when test="${sessionScope.uNames == null}">
        變數不存在(從未設定)
    </c:when>
    <c:when test="${sessionScope.uNames == ''}">
        變數存在但為空字串
    </c:when>
    <c:otherwise>
        變數有值:${sessionScope.uNames}
    </c:otherwise>
</c:choose>

實務建議

  1. 優先使用 ${!empty var} 判斷「有效值」
  2. 搭配 JSTL <c:if>、<c:choose> 進行流程控制
  3. 後端設定 session 時建議統一:session.setAttribute("uNames", value == null ? "" : value)

掌握 EL 表達式的 empty 運算子,能讓 JSP 頁面邏輯更簡潔、更安全。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved