Nested <c:forEach> in JSTL
The JSP Standard Tag Library (JSTL) core
library, provides custom tags for basic functionality. Instead of using those
hardcoded scriptlet, It allows you to program your pages using tags. While using
the scriptlet, as the program grows bigger it becomes difficult to understand
the program, and later in case if any programmer wants to change any module or
part of a code, then it becomes very difficult in understanding the
program. Here comes the use of the JSTL, which allows you to program the
pages using tags. Now if a programmer wants any change in the code, he can
change it in the tag itself. JSTL can do nearly everything that the
JSP scriptlet can do.
<c:forEach> tag is a simple way to iterate
over arrays and collections. This tag is very much similar to for loop. The tag
repeats the body of the tag for each element in the array or collection. The nested
<c:forEach> is same as loop inside the loop. This tag can be used
for more complex loops.
The code of the program is given below:
<%@ taglib prefix = "c" uri = "http://java.sun.com/jstl/core"%>
<%@ page import = "java.util.*"%>
<%Integer[] int1 = {1, 2, 3,4,5};
Integer[] int2 = {10,20,31,40,50};
List numbers = new ArrayList();
numbers.add(int1);
numbers.add(int2);
request.setAttribute("number", numbers);
%>
<html>
<body bgcolor="#FFFFCC">
<center>
<table>
<c:forEach var = "listElement" items = "${number}">
<c:forEach var ="number" items = "${listElement}">
<tr>
<font color="#000080"><td>${number}</td></font>
</tr>
</c:forEach>
</c:forEach>
</table>
</center>
</body>
</html>
|
The output of the program is given below:

Download this example.
|