Java jstl core tag foreach
The JSTL <c:forEach>
tag is used to iterate over a collection of items and perform some action for each item. This tag is part of the JSTL core tag library, and is typically used to generate dynamic HTML content based on a data source.
The basic syntax for the <c:forEach>
tag is as follows:
<c:forEach items="collection" var="variable" varStatus="status"> <!-- JSP code that references the variable and/or status objects --> </c:forEach>
The attributes of the <c:forEach>
tag are as follows:
items
: The collection of items to iterate over. This attribute is required.var
: The name of the variable to store each item in. This attribute is required.varStatus
: The name of the variable to store a status object in. This attribute is optional.
Here's an example that shows how to use the <c:forEach>
tag to iterate over a collection of strings and display each string in an unordered list:
<c:set var="myList" value="${['apple', 'banana', 'orange']}" /> <c:forEach items="${myList}" var="fruit"> - ${fruit} </c:forEach>
In this example, the <c:set>
tag is used to create a list of strings containing the values "apple", "banana", and "orange". The <c:forEach>
tag is then used to iterate over this list and display each string in an unordered list.
The resulting output of this code will be:
- apple - banana - orange
Note that the <c:forEach>
tag can also be used to iterate over other types of collections, such as arrays and maps. The <c:forEach>
tag also provides a number of other attributes for controlling the iteration, such as begin
, end
, and step
, which allow you to iterate over only a subset of the collection.