How to iterate using JSTL

The tag is the more commonly used tag because it iterates over a collection of objects. We have questionList as ArrayList and can iterated as below.

Simple Example

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:forEach> Tag Example</title>
</head>
<body>
<c:forEach var="i" begin="1" end="10">
   Item <c:out value="${i}"/><p>
</c:forEach>
</body>
</html>

Iterate for collections

<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<%
  //Arraylist with string elements
  ArrayList list = new ArrayList();
  list.add("One");
  list.add("TWO");
  list.add("Three");
  pageContext.setAttribute("listData", list);
%>

<html>
  <head>
    <title>ArrayList <c:forEach> Example</title>
  </head>
  <body>
      <c:forEach items="${listData}" var="element">
       <c:out value="${element}" />
      </c:forEach>
  </body>
</html>

Leave a Reply