Tag <c:forEach> ใช้ iterate collections, arrays, maps, ranges เป็น tag JSTL Core ที่ใช้บ่อยที่สุด
Attributes
| Attribute | คำอธิบาย | Required | Default |
| items | Collection/Array/Map/Iterator ที่จะ iterate | No | - |
| begin | เริ่มที่ index (0-based) | No | 0 |
| end | สิ้นสุดที่ index (inclusive) | No | Last element |
| step | ข้ามทุกกี่รายการ | No | 1 |
| var | Variable name สำหรับ item ปัจจุบัน | No | - |
| varStatus | Loop status object (count, index, first, last, begin, end, step) | No | - |
ตัวอย่างต่างๆ
1. Loop ตัวเลข (Range)
<c:forEach var="i" begin="1" end="5" step="1">
Item <c:out value="${i}"/><br/>
</c:forEach>
Item 1
Item 2
Item 3
Item 4
Item 5
2. Iterate List/Array
<%-- ใน controller/setAttribute --%>
<% request.setAttribute("fruits", Arrays.asList("Apple", "Banana", "Orange")); %>
<c:forEach items="${fruits}" var="fruit" varStatus="status">
${status.count}. <c:out value="${fruit}"/><br/>
</c:forEach>
1. Apple
2. Banana
3. Orange
3. Iterate Map
<c:forEach items="${userMap}" var="entry">
Key: <c:out value="${entry.key}"/>, Value: <c:out value="${entry.value}"/><br/>
</c:forEach>
4. ใช้ varStatus
<c:forEach items="${list}" var="item" varStatus="s">
<c:if test="${s.first}"><ul></c:if>
<li><c:out value="${item}"/></li>
<c:if test="${s.last}"></ul></c:if>
</c:forEach>
varStatus Properties
| Property | คำอธิบาย |
count | 1-based count |
index | 0-based index |
first | boolean - first iteration? |
last | boolean - last iteration? |
begin | begin value |
end | end value |
step | step value |
Best Practices
- ใช้
varStatus สำหรับ conditional formatting (first/last, zebra striping)
- หลีกเลี่ยง nested forEach ลึกเกินไป (performance)
items ควรเป็น Collection/Array ไม่ใช่ raw Iterator (reuse ได้)