31

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?

Jonik
  • 80,077
  • 70
  • 264
  • 372
Drew Wills
  • 8,408
  • 4
  • 29
  • 40

2 Answers2

49

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

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

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • 1
    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... – Drew Wills Aug 27 '10 at 03:27
  • That is just the way it is with JSP. I can strongly recommend upgrading to JSF and facelets. – Thorbjørn Ravn Andersen Aug 27 '10 at 06:14
  • [Here's](http://blog.smartkey.co.uk/2009/01/how-to-access-the-size-of-a-collection-in-a-jsp-page-using-jstl-el/) 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. ;-) – Jonik Sep 01 '11 at 08:58
  • @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. – Thorbjørn Ravn Andersen Sep 01 '11 at 09:27
  • @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? – Thorbjørn Ravn Andersen Mar 20 '12 at 10:15
  • @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. – Drew Wills Jul 10 '12 at 02:28
  • @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. – Jules Aug 07 '15 at 09:20
  • @Jules 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) – Thorbjørn Ravn Andersen Aug 07 '15 at 09:54
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>
Nickhil
  • 1,267
  • 10
  • 11