March 2, 2011

JSTL 1.1 - <c:forEach> example

test.jsp

Example 1:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   String[] arr = new String[] {"dog", "cat", "pig", "cow"};
   application.setAttribute("arrayAttribute", arr);
%>

<table border="1">
<c:forEach var="element" items="${arrayAttribute}" varStatus="c">
 <tr><td>${c.count}</td>
 <td>${element}</td></tr>
</c:forEach>
</table>

prints,


1dog
2cat
3pig
4cow


Example 2:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   String[] arr = new String[] {"dog", "cat", "pig", "cow", "horse", "rhino", "hippo"};
   application.setAttribute("arrayAttribute", arr);
%>

<table border="1">
<c:forEach var="element" items="${arrayAttribute}" varStatus="c" begin="1" end="5" step="2">
 <tr><td>${c.count}</td>
 <td>${element}</td></tr>
</c:forEach>
</table>

prints,


1cat
2cow
3rhino

No comments:

Post a Comment