As mentioned previously, the bodies of JSP tags can contain anything, including other JSP tags. An example is the c:out tag within the c:forEach tag in Listing 4.8. To demonstrate this further, the c:if and c:forEach tags work together in the following example.
If given an empty array, a c:forEach tag will not render its body content at all. This is fine but can lead to some odd-looking pages. In Listing 4.8, if the CD is empty, the page will display “Here are the tracks” and then stop. This is technically correct but to the user may look as though the page stopped generating halfway through. It would be better to inform the user that the CD is empty rather than to display a list with no elements. This can be accomplished by putting the c:forEach tag inside a c:if tag, as shown in Listing 4.12.
Listing 4.12 Tags working together
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <jsp:useBean id="album" beanName="tinderbox4" type="com.awl.jspbook.ch04.AlbumInfo"/> <h1><jsp:getProperty name="album" property="name"/></h1> Artist: <jsp:getProperty name="album" property="artist"/><p> Year: <jsp:getProperty name="album" property="year"/></p> <c:if test="${empty album.tracks}"> There are no tracks! What a boring CD. </c:if> <c:if test="${!(empty album.tracks)}"> Here are the tracks: <ul> <c:forEach items="${album.tracks}" var="track"> <li><c:out value="${track}"/> </c:forEach> </ul> </c:if>
Conceptually, the only new thing about this example is the check that is done in the c:if tag. The empty in the test checks whether the named property exists,3 and if it does exist and is an array, whether it has any elements. The exclamation point in the test should be read as “not.” It means that if the following test would be true, it returns false, and vice versa.