O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required