Evaluate empty or null JSTL c tags
to also check blank string, I suggest following
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:if test="${empty fn:trim(var1)}">
</c:if>
It also handles nulls
How can I validate if a String is null or empty using the c tags of JSTL?
You can use the empty
keyword in a <c:if>
for this:
<c:if test="${empty var1}">
var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
var1 is NOT empty or null.
</c:if>
Or the <c:choose>
:
<c:choose>
<c:when test="${empty var1}">
var1 is empty or null.
</c:when>
<c:otherwise>
var1 is NOT empty or null.
</c:otherwise>
</c:choose>
Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator ${condition? valueIfTrue : valueIfFalse}
:
<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />
To learn more about those ${}
things (the Expression Language, which is a separate subject from JSTL), check here.
See also:
- How does EL empty operator work in JSF?
if you check only null or empty then you can use the with default option for this:
<c:out default="var1 is empty or null." value="${var1}"/>