Java – Rendering a nested list with JSP

javajspjstl

I need to render a 3-level deep list of items via JSP. Let's say I have beans with String properties "Country", "City", "Street". I need to build a heirarchy of UL and LI tags to show streets such that they are listed under the appropriate city, and such that each city is listed under the appropriate country.

Example:

<ul>
<li>United States
    <ul>
    <li>Washingron
            <ul>
        <li>Independence Ave</li>
        <li>23d Street</li>
        </ul>
    </li>
    <li>Detroit
        ...
    </li>
    </ul>
</li>
<li>United Kingdom
...
</li>
</ul>

Obviously, I could use forEach, but properly opening and closing tags for each list would require tons of if statements. Is there some simple way to do this via JSTL?

Best Answer

<ul>
<c:forEach items="${countriesList}" var="country"> 
   <li>${country.name}
      <ul>
         <c:forEach items="${country.stateList}" var="state">
            <li>${state.name}
                <ul>
                   <c:forEach items="${state.addressLines}" var="addressLine">
                      <li>${addressLine.addressString}</li>
                   </c:forEach>
                </ul>
            </li>
         </c:forEach>
      </ul>
   </li>
</c:forEach>
</ul>