JSTL / EL equivalent of testing for null and list size?

30,131

Solution 1

Use the empty keyword, it checks both nullness and emptiness.

<c:if test="${not empty sokandeList}">
    ...
</c:if>

Note that when your intent is to iterate over the list using <c:forEach> then it may be good to know that it already won't run when the provided items is empty. If the <c:forEach> is directly surrounded by this check, then this check is entirely superfluous.

See also:

Solution 2

Here's one way:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(sokandeList) > 0}">

I think you can use this too:

<c:if test="${!empty myObject.sokandeList}">

Awesome JSTL cheat sheet

Share:
30,131
Niklas Rosencrantz
Author by

Niklas Rosencrantz

I'm as simple as possible but not any simpler.

Updated on May 25, 2020

Comments

  • Niklas Rosencrantz
    Niklas Rosencrantz almost 4 years

    Possible Duplicate:
    Evaluate empty or null JSTL c tags

    I'm refactoring scriptlets to JSTL and EL and I would like to know how to write the following in JSTL / EL:

    if(sokandeList != null && sokandeList.size() > 0) { %>
    ...
    

    I don't know how to test for null and AFAIK EL can only access getters in this context so I must add a method getSize() to the sokandeList class. Correct? What should the JSTL / EL expression look like? Thanks for any help