بیشترلیست موضوعات • Index • ExamplesApache Jakarta and Beyond: A Java Programmers Introduction By
Larne Pekowsky Publisher : Addison Wesley Professional Pub Date : December 30, 2004 ISBN : 0-321-23771-4 Pages : 608
توضیحاتافزودن یادداشت جدید
18.6. Iteration in a Page
It was mentioned previously that the expression language can handle compound values, meaning that an expression like
${aBean.values[1]}
would be legal if aBean has a property called values and that values is an array or List with at least two elements.
Errors to Watch For
If a request is made for an index beyond the number of elements in the array, the result will be empty.
It is unusual to need to access a particular element in an array, but it is more common to have to repeat some action for every element, regardless of how many there are. There is a tag in the standard library that handles such iteration, called c:forEach.Listing 18.12 uses the c:forEach tag to show some information from a serialized bean holding information about an album, including the set of tracks.
Listing 18.12. The forEach tag
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <jsp:useBean id="album" beanName="tinderbox" type="com.awl.jspbook.chapter19.AlbumInfo"/> <h1><c:out value="${album.name}"/></h1> Artist: <jsp:getProperty name="album" property="artist"/><p> Year: <c:out value="${album.year}"/></p> Here are the tracks: <ul> <c:forEach items="${album.tracks}" var="track"> <li><c:out value="${track}"/> </c:forEach> </ul>
This example also illustrates a new feature of the jsp:useBean tag: the ability to load a serialized bean. This is accomplished by specifying a beanName, which will cause jsp:useBean to load a file with that name ending in .ser from the CLASSPATH. The result of Listing 18.12 is shown in Figure 18.2.
Figure 18.2. Iteration used to display every element in an array.
The c:forEach tag takes a number of parameters. The first is the items to iterate over, which is specified by a script. The second is a name to use as a variable; within the body of the c:forEach, this variable will be set to each element in the array in turn. This variable can be accessed by the expression language just as a bean, which means among other things that the c:out tag can be used to display it.
Errors to Watch For
If a nonarray is used as the items parameter, the c:forEach tag will treat it as if it were an array with one element.