JSTL ForEach Loop/ Array or List

NewQueries picture NewQueries · Mar 4, 2013 · Viewed 29.1k times · Source

I needed to loop through items but I am also looking for a way to get the next or previous element in the items list so that as you can see below, I can check if the second item starts with the first item. Is there a way I can store the elements like in List or Array?

   <c:forEach var="item" items="${entry.value.options}">                        
                    <c:set var="upper" value="${item.key }"/>
                    <c:choose>
                        <c:when test="${fn:startsWith(item, upper)}">
                            <c:if test="${item ne upper} }">
                                <ul>
                                    <li>
                                        <input class="parent" type="checkbox" name="criterias[${entry.key}]" value="${item.key}" />
                                        <label>${item.value}</label>
                                    </li>                                       
                                </ul>
                            </c:if>
                        </c:when>
                        <c:otherwise>
                        <li>
                            <input class="child" type="checkbox" name="criterias[${entry.key}]" value="${item.key}" />
                            <label>${item.value}</label>
                        </li>       
                        </c:otherwise>
                    </c:choose>             
    </c:forEach>    

Thanks a lot!

Answer

Alex picture Alex · Mar 4, 2013

You can pass to jsp a structure like List<Item> list where Item has own ArrayList and then use inner forEach. It could be easier than having flat structure.

<c:forEach var="item" items="${list}">
Access here item if needed <c:out value="${item.value}"/>
   <c:forEach var="elem" items="${item}">
   ...
   Access here elem <c:out value="${elem.value}"/>
   ...
   </c:forEach>
</c:forEach>