在 JSP 中使用 EL 表達式 ${sessionScope.uNames} 時,常需判斷變數是否存在或為空。直接使用 if (xx != null) 或 xx.equals("") 在 EL 中無法正常運作。
<c:if test="${!empty sessionScope.uNames}">
<!-- uNames 有值且非空 -->
歡迎,${sessionScope.uNames}!
</c:if>
<c:if test="${empty sessionScope.uNames}">
<!-- uNames 為 null、空字串、空集合、空陣列 -->
請先登入
</c:if>
empty 運算子會回傳 true 的情況:
null""new String[0]Collections.EMPTY_LISTCollections.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>
<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>
${!empty var} 判斷「有效值」<c:if>、<c:choose> 進行流程控制session.setAttribute("uNames", value == null ? "" : value)掌握 EL 表達式的 empty 運算子,能讓 JSP 頁面邏輯更簡潔、更安全。