Reputation: 3538
(I am using jstl version 1.2 and java 6)
I am working with some legacy code that has some logic in its jsp pages, that aside I now need to loop over a list of data, match on something and then set a variable to list value (ArrayList in this case). The reason I need to do this is to then loop over the list I found later on in the jsp file.
Here is the snippet of code I have so far, but does not work:
<c:set var="listOfChildData" value="${[]}" scope="page"/>
<c:forEach items="${otherListOfData}" var="data">
<c:if test="${data.id == dataToMatchOn.id}">
<c:catch var="exception">${data.children}</c:catch>
<c:if test="${empty exception}">
<c:set var="listOfChildData" value="${data.children.toArray()}" scope="page"/>
</c:if>
</c:if>
</c:forEach>
Do I need to manually go through each item in the list and add it to the listOfChildData
?
Reading around, all the examples I found were of creating an array variable from scratch and not from another variable.
If this comes down to using scriptlets, can I do that within a forEach
loop?
Updated to include exception handling if data.children
is null, empty, etc.
Upvotes: 1
Views: 2061
Reputation: 23246
You don't need to copy the list. All you need to set is the selectedItem and then you can work with this:
<c:forEach items="${otherListOfData}" var="data">
<c:if test="${data.id == dataToMatchOn.id}">
<c:set var="selectedItem" value="${data}/>
</c:if>
</c:forEach>
<p>From here on I can work with the selected item:</p>
${selectedItem.children}
Upvotes: 2