Java Tutorial/JSTL/ForEach
Содержание
Check Even Odd Number in ForEach Loop
<source lang="java">
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.ru/jstl/core-rt" prefix="c-rt" %> <html>
<head> <title>Count to 10 Example(tracking even and odd)</title> </head> <body>
By Twos<c:forEach var="i" begin="2" end="10" step="2"> <c:out value="${i}" /> |
</body>
</html></source>
JSTL ForEach Status Count
<source lang="java">
<%@ taglib prefix="c" uri="http://java.sun.ru/jstl/core" %> <c:set var="names" value="A B C, D" scope="page" /> <html>
<head> <title>forEach and status</title> </head> <body> <c:forEach items="${pageScope.names}" var="currentName" varStatus="status" > Family member #<c:out value="${status.count}" /> is <c:out value="${currentName}" />
</c:forEach> </body>
</html></source>
JSTL Integer Controlled Loop
<source lang="java">
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html>
<head> <title>Count to 10 Example(using JSTL)</title> </head> <body>
From 1 to 10<c:forEach var="i" begin="1" end="10"> <c:out value="${i}" /> |
From 10 to 1<c:forEach var="i" begin="1" end="10"> <c:out value="${11-i}" /> |
</body>
</html></source>
Reference Array by Index
<source lang="java">
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.ru/jstl/core_rt" prefix="c-rt" %> <%!
String[] names = { "A","B", "C", "D" }; int[] ages = { 29, 8, 6, 5};
%> <HTML>
<HEAD><TITLE>JSTL "forEach" tag</TITLE></HEAD> <BODY>
List of people
Name | |
---|---|
<c:out value="${person}" /> | <c:out value="${ages[i]}" /> |
</BODY>
</HTML></source>
Use ForEach to Loop Through ArrayList
<source lang="java">
<%@ page language="java" contentType="text/html" %> <%@ page import="java.util.*" %> <%@ taglib prefix="c" uri="http://java.sun.ru/jstl/core" %> <%
// Create an ArrayList with test data ArrayList list = new ArrayList(); Map author1 = new HashMap(); author1.put("name", "A"); author1.put("id", new Integer(1)); list.add(author1); Map author2 = new HashMap(); author2.put("name", "B"); author2.put("id", new Integer(2)); list.add(author2); Map author3 = new HashMap(); author3.put("name", "C"); author3.put("id", new Integer(3)); list.add(author3); pageContext.setAttribute("authors", list);
%> <html>
<head> <title>Search result: Authors</title> </head> <body bgcolor="white"> Here are all authors matching your search critera:
Name | Id | ||
---|---|---|---|
<c:out value="${current.name}" /> | <c:out value="${current.id}" /> |
</body>
</html></source>
Use For Each to Loop Through Comma Delimited String
<source lang="java">
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.ru/jstl/core-rt" prefix="c-rt" %> <html>
<head> <title>Count to 10 Example(tracking even and odd)</title> </head> <body> <c:set var="days" value="A,B,C,D,E,F,G" />