JSTL For Example

JSTL For Example explains about How to use JSTL for loop over a collection. 

Consider an example where you need to loop over a collection or an array using JSTL tags.

In order to iterate over a collection or an array,  you can use JSTL c:forEach tag, for this you need to pass a collection / array into items tag inside c:forEach core function

Using JSTL for tag('c:forEach'), you can get options to iterate over arrays and collections

Below you can view the two jstl examples, where first one is a basic for loop printing 1 to 20 numbers, and second example is showing how to loop over a collection

Required Libraries

You need to download

  1. Tomcat 9
  2. JSTL 1.2

Following jar must be in classpath

  1. jstl-1.2.jar

JSTL For Loop

<c:forEach var="i" begin="1" end="20" step="1" varStatus ="status">
    <c:out value="${i}" /> 
</c:forEach>
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

JSTL For (Iterating Collection)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.util.ArrayList"%>
<%
    ArrayList<String> numList = new ArrayList<String>();
    numList.add("one");
    numList.add("two");
    numList.add("three");
    request.setAttribute("numList", numList);
%>
<html>
<body>
    <c:forEach items="${numList}" var="item" varStatus="status">
        ${status.count}) ${item}<br/>
    </c:forEach>
</body>
</html>
Output
1) one

2) two

3) three

 









Your email address will not be published. Required fields are marked *