Looping without scripting

Imagine you want something that loops over a collection (say, an array of catalog items), pulls out one element at a time, and prints that element in a dynamically-generated table row. You can’t possibly hard-code the complete table—you have no idea how many rows there will be at runtime, and of course you don’t know the values in the collection. The <c:forEach> tag is the answer. This does require a very slight knowledge of HTML tables, but we’ve included notes here for those who aren’t familiar with the topic.

By the way, on the exam you are expected to know how to use <c:forEach> with tables.

Servlet code

...
 String[] movieList = {"Amelie", "Return of the King", "Mean Girls"};
 request.setAttribute("movieList", movieList);
...

Note

Make a String[] of movie names, and set the array as a request attribute.

What you want

image with no caption

In a JSP, with scripting

<table>
<% String[] items = (String[]) request.getAttribute("movieList");
   String var=null;
   for (int i = 0; i < items.length; i++) {
      var = items[i];
 %>
  <tr><td><%= var %></td></tr>
  <% } %>
</table>

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.