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

感情迁移 提交于 2019-12-04 08:26: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?


回答1:


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

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




回答2:


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>


来源:https://stackoverflow.com/questions/3579548/access-the-size-of-a-collection-in-jsp-jstl-el

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!