<c:forEach> tag in JSTL is used for executing the same set of statements for a finite number of times. It’s similar to the for loop in java. This is basically used when we need to perform(execute) set of statements again and again for a specified number of times.
<c:forTokens> is also used for iteration but it only works with delimiter which means using this tag we can break the input data into multiple parts based on the delimiter. We will understand this with the help of an example in this post.
<c:forEach> Tag
Syntax of <c:forEach>
<c:forEach var="counter_variable_name" begin="intial_value" end="final_limit"> //Block of statements </c:forEach>
The below are the three main attributes of <c:forEach> tag.
begin: The initial counter value.
end: The final limit till which the loop will execute
var: Counter variable name
Example
In this example we are printing value of variable counter in loop using <c:forEach> tag. The loop is starting from value 1 (mentioned in begin attribute) and ending at value 10 (value of end attribute).
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Example c:forEach tag in JSTL</title> </head> <body> <c:forEach var="counter" begin="1" end="10"> <c:out value="${counter}"/> </c:forEach> </body> </html>
Output:
<c:forTokens> tag
Syntax of <c:forEach>
<c:forTokens items="value(s)" delims="delimiter" var="variable_name"> //Set of statements </c:forTokens>
The below are the three main attributes of <c:forTokens> tag.
items: Set of data value(s).
delims: The delimiter can have any value. It can be a number, string or special character.
var: variable name which stores the sub strings.
Example
In this example we are splitting the strings into multiple substrings using delimter dot(‘.’).
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Example c:forTokens tag in JSTL</title> </head> <body> <c:forTokens items="www.beginnersbook.com" delims="." var="site"> <c:out value="${site}"/> </c:forTokens> </body> </html>
Output:
Nizamuddin Shaikh says
I am a new comer to JSP. While running c:forEach example on Tomcat 8 I got following message:
HTTP Status 500 – The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
I shall be grateful if you guide me further.
Thanks.
Diego says
You gotta import the library (take jstl.jar , copy and paste it to the lib folder under WEB-INF, finally right click it and select ‘Build Path’->’Add To Build Path’).
Note : the jar name differs from the one above mentioned depending on the versions. These steps should be executed in case you are using Eclipse IDE