ChatGPT解决这个技术问题 Extra ChatGPT

Check a collection size with JSTL

How can I check the size of a collection with JSTL?

Something like:

<c:if test="${companies.size() > 0}">

</c:if>

M
Martlark
<c:if test="${companies.size() > 0}">

</c:if>

This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt instead of >.

<c:if test="${companies.size() gt 0}">

</c:if>

If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length() function then. From the documentation:

length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.

Put this at the top of JSP page to allow the fn namespace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Or if you're using JSPX or Facelets:

<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">

And use like this in your page:

<p>The length of the companies collection is: ${fn:length(companies)}</p>

So to test with length of a collection:

<c:if test="${fn:length(companies) gt 0}">

</c:if>

Alternatively, for this specific case you can also simply use the EL empty operator:

<c:if test="${not empty companies}">

</c:if>

Just wanted to note that if the need to get the size is to determine if the collection is non empty then the "empty" operator is useful since it also checks for null.
I agree with Mark here. Why import more cruft into your page for one tag? Use Mark's solution, it's cleaner.
Agreed - empty is cleaner. @Joel should post as a full answer so it can be voted up and accepted. A lot of us here (me) are non-jsp programmers copy/pasting together snippets from Google and SO without much thought beyond the first piece of code we see.
The OP asked about checking the size, not necessarily about checking if it is empty, my answer also allows more complicated scenarios to be contemplated with the full tag library available.
Thanks, mate. It was really helpful as I wanted to display the list only when the size was more than one.
J
Josh

As suggested by @Joel and @Mark Chorley in earlier comments:

${empty companies}

This checks for null and empty lists/collections/arrays. It doesn't get you the length but it satisfies the example in the OP. If you can get away with it this is just cleaner than importing a tag library and its crusty syntax like gt.


B
Brad Larson

You can use like this

${fn:length(numList)}

S
Supun Dharmarathne

use ${fn:length(companies) > 0} to check the size. This returns a boolean