Updated April 20, 2023
Introduction to JSP foreach
JSP Foreach tag is used to iterate through the loop until a false condition is met. This is used in JSP in case we need to show a value from the array containing multiple values. For this tag to work, we should have an array of collections like List /Sets should be declared as a prerequisite as foreach requires an array as an input parameter to iterate through. It works like a “for” loop with a condition of “until we reach the end of array“ in JAVA 5 or C. This is enabled by the use of tag <c:forEach> closed by closing tag </c:forEach>. This tag can be included in the JSP page with the help of the JSTL library. We need to make sure to include JSTL’s latest library in the web content folder’s “WEB-INF” Folder for this tag to work. Let’s understand this tag more with the help of syntax and examples for this tag given in the below sections.
Syntax
The syntax for Foreach tag in JSP is as follows:
An array/set/list with the list of values that should be declared first. The keywords “pageContext” and “pageScope” is used to extract the attributes and variables for the declared array. The for loop tag with the attributes “var” and “items” are used to get the values till null is attained in the array.
String[] var = new String[]{"1" , "2", "3", "4", "5", "6", "7"};
pageContext.setAttribute("variables", var);
<c:forEach var="var" items="${pageScope.variables}" varStatus="status", begin=””, end=””, step="">
<c:out value="${var}"/>
</c:forEach>
Here only “var” and “items” attributes are mandatory to be assigned with the values while other attributes “begin, end, step, varStatus” may or may not be declared as they have defaulted.
How Foreach Works in JSP?
Foreach tag contains two attributes as mentioned in the above section “syntax”. These two attributes are used to get the items and the condition where this loop should stop (That is null) is defined inside the foreach tag itself which is stored in the JSTL library. The variables should be stored in JSTL keywords “pagescope” and “pageContext” to be used in the foreach tag.
Some prerequisites to be declared to make use for each loop are enlisted below:
- JSTL library should be imported and applied to the project.
- In the jsp page, the taglib tag should be used to inherit the dependencies to use the JSTL library.
- A set, list, or array should be declared and assigned with the values for the “foreach” loop to function.
Examples
Here are the following examples mention below
Example #1
Code:
<%@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>JSP Foreach tag example page</title>
</head>
<body>
<h2>This page is designed to demonstrate the use of foreach tag in JSP: </h2>
<jsp:scriptlet>
String[] var = new String[]{"Number 1" , "Number 2", "Number 3", "Number 4", "Number 5", "Number 6", "Number 7"};
pageContext.setAttribute("variables", var);
</jsp:scriptlet>
<%-- JSP foreach tag --%>
<c:forEach var="var" items="${pageScope.variables}">
<c:out value="${var}"/> <br> <br>
</c:forEach>
</body>
</html>
Output:
Explanation:
In this example, an array named “var” is created with the values in a string. Pagecontext keyword from the JSP library is used to set the attributes where the array “var” is assigned to the variable named “variables”. The foreach tag starts with the tag “<c:forEach > and ends with the closing tag “</c:forEach>”. The attributes are added to the tag. The mandatory attributes are “var” and “items” which are assigned with the values. “var” contains the array name “var” which is used to iterate through the values and the “items” contains the values which will be used as a comparison factor with null. The sign “$” denotes that the value keeps changing. The values in “items” can be extracted from an array with the help of the “pageScope” keyword. This keyword is used in conjunction with variables declared in the “pageContext” keyword. Finally, the values are printed using the <c:out> tag.
Example #2
Code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Foreach tag example-2 page</title>
</head>
<body>
<h1>This page is designed to demonstrate the second example of foreach tag in JSP: </h1>
<form name="forEachForm"
action="${pageContext.request.contextPath}/test2JSPfile.jsp"
method="POST">
Select the color: <br/>
Blue <input type="radio" name="langChoice" value="Blue"/><br/>
Red <input type="radio" name="langChoice" value="Red"/><br/>
Black <input type="radio" name="langChoice" value="Black"/><br/>
Green <input type="radio" name="langChoice" value="Green"/><br/>
Yellow <input type="radio" name="langChoice" value="Yellow"/><br/>
Orange <input type="radio" name="langChoice" value="Orange"/><br/>
Brown <input type="radio" name="langChoice" value="Brown"/><br/><br/>
<input type="submit" value="Submit"/>
</form>
<br/>
<br/>
Selected items are displayed here:
<c:forEach var="lang" items="${paramValues.langChoice}">
<font color="#008000"><c:out value="${lang}"/>,</font>
</c:forEach>
</body>
</html>
Output:
Explanation:
This code also contains an array with the string of color names. All the strings are assigned with a radio button. Once the radio button is selected and the submit button is clicked then the selected color will be displayed at the end of the page. The form tag is used so that radio buttons and its value can be recorded and passed in the submit button as information. This information is then passed to the display section at the end of the page with the help of a foreach tag in JSP. Here the keywords named “pageContext” and paramValues are used to record the values and display in the foreach section.
Conclusion
JSP Foreach tag is used to make page dynamics after its introduction in the JSTL library. This provides clear code with the help of simple tags. This functionality eliminates the use of for loops written traditionally under JSP which increased the clutter of JAVA code. The use of the foreach loop looks a bit complicated at the start for coders but understanding the attributes and use of keywords like “pageScope” associated makes it easier to understand the code and removes the unnecessary JAVA clutter in the form of JSP for loops.
Recommended Articles
This is a guide to JSP foreach. Here we discuss how Foreach Works in JSP along with respective examples for better understanding. You may also have a look at the following articles to learn more –