Chapter 4. Iteration ActionsTopics in This Chapter
In any programming language, the ability to iterate over a set of values is essential. Before JSTL, JSP did not provide an explicit means to accomplish that fundamental task, so developers had two choices: use a scriptlet or implement a custom action, neither of which is very attractive.JSTL provides two actions that iterate over a set of values: <c:forEach> and <c:forTokens>. JSTL also exposes an interface and two classes that you can use to implement custom iteration actions: LoopTag, LoopTagSupport, and LoopTagStatus, respectively.[1] This chapter describes the <c:forEach> and <c:forTokens> actions and shows you how to implement custom actions using the LoopTag interface and the LoopTagSupport and LoopStatus classes. [1] LoopTag, LoopTagSupport, and LoopTagStatus all reside in the javax.servlet.jsp.jstl.core directory. To iterate over a set of values with a scriptlet, you must be proficient in the Java programming language and you must also understand how Java and HTML interact within JSP pages. For example, consider the following code fragment:
The preceding scriptlet iterates over an array of ints stored in request scope. That scriptlet is short, but it requires you to be familiar with the following constructs:
Even for seasoned Java developers, it's not uncommon to forget the required cast in the preceding code fragment. If you are a page author and you're not familiar with the constructs listed above, or if you're a veteran Java developer and you want to avoid scriptlets, the JSTL iteration actions are for you. Consider the simplicity of the following code fragment, which is functionally identical to the preceding scriptlet:
The preceding code fragment uses the Iterating Over Data Structures" on page 158 for more information about iterating over maps with <c:forEach>. Figure 4-1 shows a JSP page that contains both of the preceding code fragments. Figure 4-1. Looping Over Primitive Types with a Scriptlet vs. Looping with JSTL![]() The JSP page shown in Common Mistakes" on page 95 for more information about missing taglib declarations. Listing 4.1 Looping with a Scriptlet vs. Using JSTL
![]() |