tags:

views:

2495

answers:

5

I managed to do it with the next code but there must be an easier way.

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


<c:if test="${fn:length(attachments) > 0}">
    <c:forEach var="attachment" items="${attachments}" varStatus="loopCount">
        <c:if test="${loopCount.count eq 1}">
         attachment.id
        </c:if>
    </c:forEach>
</c:if>
+3  A: 

You can access individual elements with the array [] operator:

<c:out value="${attachments[0].id}" />

This will work for arrays, lists and sets. It won't work for maps. In that case you must put the key of the element inside the brackets.

kgiannakakis
I get the next error javax.el.PropertyNotFoundException: Property '0' not found on type org.hibernate.collection.PersistentSet
Sergio del Amo
The above will only work for collections types that have a get(int i) method. Is this possible with PersistentSet?
kgiannakakis
A: 

You could create a custom function.

Summers Pittman
+2  A: 

Work for arrays and lists only, not for set.

The index is irrelevant in a `Set`. A `Set` is by nature unordered (certain implementations aside, but that's not the contract of the `Set` itself). If you want an ordered collection, just use `List` or an array.
BalusC
A: 

Hello,

Using ${mySet.toArray[0]} does not work.

I do not think it is possible without having forEach loop at least one iteration.

prx
A: 

${mySet.toArray().getAt(0)}

Nick
This only requires 3rd party vendor specific enhanced EL support since it is not part of Java EE API. As far JBoss AS is the only which supports this so this code may not run at Tomcat, Glassfish, WebSphere, etc.
BalusC