Monday, July 26, 2021

JSTL foreach tag example in JSP - looping ArrayList

JSTL  foreach loop in JSP
JSTL  foreach tag is pretty useful while writing Java free JSP code.  JSTL foreach tag allows you to iterate or loop Array List, HashSet or any other collection without using Java code. After the introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages. JSTL foreach tag is a replacement of for loop and behaves similarly like foreach loop of Java 5 but still has some elements and attribute which makes it hard for first-timers to grasp it. JSTL foreach loop can iterate over arrays, collections like List, Set and print values just like for loop.

In this JSP tutorial, we will see a couple of example of foreach loop which makes it easy for new guys to understand and use foreach loop in JSP. By the way, this is our second JSP tutorial on JSTL core library, in the last tutorial we have seen How to use core <c:set> tag in JSP page.



How to use forEach tag in JSP page

JSTL foreach tag example in JSPforEach tag is part of standard JSTL core package and written as <foreach> or <c:foreach> or <core:foreach> whatever the prefix you are using in taglib directive while importing JSTL core library. 

In order to use foreach tag in JSP pages you need to import JSTL tag library in jsp and also need to include jstl.jar in your WEB-INF/lib directory or in Java classpath. if you are using Eclipse or Netbeans IDE then it will assist you on code completion of foreach tag otherwise you need to remember its basic syntax as shown below:

Syntax of foreach tag in JSTL

<c:forEach var="name of scoped variable"
           items="Colleciton,List or Array"  varStatus="status">



where var and items are manadatory and varStatus, begin, end or step attributes are optional. Here is an example of foreach tag:

<c:forEach var="window" items="${pageScope.windows}">
    
<c:out value="${window}"/> 
</c:forEach>

above JSTL  foreach tag is equivalent to the following foreach loop of Java 1.5

foreach(String window: windows){
   System.out.println(window);
}

JSTL foreach tag examples

In this section of the JSTL tutorial, we will see some more examples of using a foreach tag in the JSP page for looping purposes. Just try a couple of examples and you will get hold of foreach it looks easier after trying a few examples.

Iterating over collections or List using JSTL forEach loop

In order to iterate over collections e.g. List or Set you need to create those collections and store that into any scope mentioned above e.g. pageScope and than access it using expression language like ${pageScope.myList}. see the JSP page in last example for complete code example of foreach tag.

Iterating over array using JSTL  forEach loop

For iterating over an array e.g. String array or integer array in JSP page,  "items" attribute must resolved to an array. You can use expression language to get an Array stored in of scope available in JSP e.g. page scope, request scope, session or application scope. 

These are different than bean scope in Spring MVC and don’t confuse between Spring bean scope and JSP variable scope if you are using Spring MVC in your Java web application. Rest of foreach loop will be similar to foreach loop example of iterating over Collections in Java.


JSTL  foreach example using varStatus variable

varStatus attribute declare name of variable which holds current looping counter for foreach tag. It also expose several useful information which you can access using varStatus e.g. what is current row, whether you are in last row etc. Here is a code example of how to use varStatus in foreach JSTL tag on JSP:

<%-- JSTL foreach tag varStatus example to show count in JSP  --%>
<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >
    
<c:out value="count: ${loopCounter.count}"/>
    <c:out value="${window}"/>
</c:forEach>

Output:
JSTL foreach tag example in JSP
count: 1 Windows XP
count: 2 Windows 7
count: 3 Windows 8
count: 4 Windows mobile


Some other handy properties are : first, last, step, begin, end, current, index and count

Nested foreach tag example in JSP JSTL

Another good thing of JSTL foreach tag is you can nest foreach tag loop inside another foreach tag which is quite powerful way of looping without using scriptlets in JSP. Here is an example of nesting foreach tag in JSP JSTL tag library:

<%-- JSTL foreach tag example to loop an array in JSP and nesting of foreach loop --%>
<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >
   
<c:out value="outer loop count: ${loopCounter.count}"/> 
   <c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" > 
       
<c:out value="inner loop count: ${loopCounter.count}"/>
  
</c:forEach>
</c:forEach>

Output:
outer loop count: 1
inner loop count: 1
inner loop count: 2
outer loop count: 2
inner loop count: 1
inner loop count: 2

Complete JSTL  foreach loop example in JSP

Here is complete JSP page which shows how to use JSTL foreach tag for looping over String array . Similarly you can loop over any Collection e.g. List or Set as well.

<%@page import="java.util.List"%>
<%@page import="java.util.Arrays"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
   
<head>
      
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      
<title>Welcome to JSTL foreach tag Example in JSP</title>
   
</head>

   
<body>
       
<h2>JSTL foreach tag example in JSP</h2>

        
<jsp:scriptlet>
            String[] windows = new String[]{"Windows XP", "Windows 7", "Windows 8", "Windows mobile"};
            pageContext.setAttribute("windows", windows);
       
</jsp:scriptlet>

        
<%-- JSTL foreach tag example to loop an array in jsp --%>
        
<c:forEach var="window" items="${pageScope.windows}"> 
            <c:out value="${window}"/> 
        </c:forEach>
   
</body>
</html>

Output:
JSTL foreach tag example in JSP
Windows XP
Windows 7
Windows 8
Windows mobile


That’s all on How to use JSTL forEach loop example in JSP page. We have seen JSTL foreach tag example of Iterating or looping over Array, List, Collection, and nesting of two forEach loop which allows you to write powerful JSP pages without using any Java code.


Other JSP tutorials from Javarevisited you may like

7 comments :

Anonymous said...

Great Example of JSTL foreach tag Javin, Just to add my 2 cents and improve reference of c:foreach tag attributes, it accepts 6 attributes e.g. items, begin, end, step, var, and varStatus.

items - Collection to iterate
var - variable which hold current item in loop
begin - begin index, starts with 0,
end - end index, defaults to last element
step - loop increment variable, defaults to 1
varStatus - variable to export foreach loop status.

I agree with you that, it's not easy to remember attributes of any core JSTL tag, but this reference certainly helps. One more thing, these attributes are also hold similar meaning in another JSTL loop tag forTokens or c:forTokens, which is very helpful to iterate over comma separated Strings in JSP.


Sunidhi said...

Hi Javin, I have to create an HTML table by looping over HashMap in JSP, i.e. displaying key and value in two different column. I need to do this without scripting i.e. I can not use scriptlet? I am not sure, how I can use tag to iterate over Map, as It's not a Collection like List. Can you please post an example to loop over Map in JSP?

Unknown said...

i also have a one problem, i m using two tables one is question and second one is option so i want to get the option according to questionid whn i m giving as manaully questionid then i m getting that same options wid diff question so i want to provide there somthng like question id should get as i and i shuld get incremented every time so any body can help me...

Anonymous said...

If the servlet puts an object named "lesfruits" wich is an ArrayList in the request, here is a way to display the ArrayList items in a jsp:


${i}


Anonymous said...

JSTL forEach() tag is great for generating HTML tables, all you need is two forEach(), one to print rows and other to print columns and you have a nice, dynamic HTML table ready without using any third paty tag library like display tag.

man man said...

I want to print a table content in jsp..multiple tables are mapped.in that i need to print multiple data in a single column.for example i alloted 3 vehicles,and i need to display no of vehicles 3 in one column and registration numbers of that vehicles in another single column using comma seperation

Syed parveen said...

I have one issue while alignment the labels. Total I have 7labels if I enable 5 fields one should comes center and other 4 will be in next line. And in mobile view 2should bi on top another 3in next line.
Like this can you please help me on this issue I am using Jsp

Post a Comment