Search code examples
jspjstlnested-object

How to print nested objects using JSTL?


How does one go about printing the values of a nested object/property in a map on a JSP page using JSTL?

<c:foreach items="${survey}" var="survey">
    <c:out value="${survey.value}" />
</c:foreach>

Survey has a property called Questions, which is another bean, and I want to print those questions survey.questions.getId() or survey.questions.getTitle()), how would that <c:forEach> statement look like?

In my case, ${survey} is a Map not a Collection.


Solution

  • If your nested property is a single object instance, you just reference it directly, like:

    <c:forEach var="surveyItem" items="${surveys}">
        ${surveyItem.title} <!-- You can use the c:out if you really want to -->
    </c:forEach>
    

    That assumes that you have a collection of Survey objects bound to the surveys attribute, and that each Survey has a title. It will print the title of each survey.

    If your nested property is a collection of objects, then you use a forEach loop to iterate them, just like in your example.

    <c:forEach var="question" items="${survey.questions}">
        ${question.title} 
    </c:forEach>
    

    That will print the title of each Question, assuming that you have a single Survey object bound to the survey attribute, and that the Survey object has a collection of Question objects as a field (with an appropriate getter method, i.e. getQuestions()).

    You can also have nested loops, like:

    <c:forEach var="surveyItem" items="${surveys}">
        ${surveyItem.title}
        <c:forEach var="question" items="${surveyItem.questions}">
            ${question.title} 
        </c:forEach>
    </c:forEach>
    

    That will print the title of every Survey along with the title of each Question in each Survey.

    And if for some reason you decide to pass a Map, you can do:

    <c:forEach var="entry" items="${surveyMap}">
        Map Key:  ${entry.key}
        Map Value:  ${entry.value}
        Nested Property:  ${entry.value.title}
        Nested Collection:
        <c:forEach var="question" items="${entry.value.questions}">
            ${question.title}
        </c:forEach>
    </c:forEach>