Access the size of a collection in JSP/JSTL/EL [duplicate]
Asked Answered
B

2

30

I have a List variable called services in my JSP page. I need to add some markup to the page if there's more than 1 element in the list.

What I'd like to do is...

<c:if test="${services.size() gt 1}">
  <!-- markup... -->
</c:if>

But you can't invoke methods on Java objects in EL (I think this is perhaps the 364823782 time I've regretted that fact). You can only access getters on Java objects by dropping the 'get,' e.g. ${user.name} for a User class that has a getName() method.

What's the right way to evaluate this test?

Broderick answered 26/8, 2010 at 21:10 Comment(0)
L
48

You are looking for fn:length(services). Remember to define the fn namespace.

http://download.oracle.com/javaee/5/tutorial/doc/bnalg.html

Lanceolate answered 26/8, 2010 at 21:15 Comment(8)
It's the right answer, but it's not the sort of answer I was really hopping for. What a pain. Why can't we have Groovy or Rhino instead of EL...Broderick
That is just the way it is with JSP. I can strongly recommend upgrading to JSF and facelets.Patriciapatrician
Here's a nice blog post about the same problem (that arrives to the same solution). I agree that JSP/EL suck, and can recommend upgrading to Wicket. ;-)Cirrose
@Jonik, the primary advantage of JSF as opposed to Wicket is being part of standard Java EE 6. This may and may not be important to you.Patriciapatrician
@DrewWills it appears that EL (the language your expression is written in) supports method calls in the version shipping with Java EE 6. Would that be an option?Patriciapatrician
@Thorbjørn Ravn Andersen -- I'm so glad to hear that! I'm sure it will become an option in the next couple quarters... for when I hit this snag again.Broderick
@ThorbjørnRavnAndersen unfortunately it doesn't support it for collections, as the "a.b" syntax is interpreted as an alias for "a[b]" which means it is interpreted as an attempt to access the value at a particular index.Gravante
@Gravante it's been a while, but if I recall correctly you need parenthesis to indicate you want a method call (where you may provide parameters)Patriciapatrician
M
17

Include the tag lib in jsp file

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

Use

<c:if test="${fn:length(services) gt 1}">
<!-- markup... -->
</c:if>
Microseism answered 2/9, 2014 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.