How does one go about printing the values of a nested object/property in a map on a JSP page?
<c:foreach items="${survey}" var="survey">
<c:out value="${survey.value}" />
</c:foreach>
So let's say Survey has a property called Questions (which is another object) and I want to print those questions (survey.questions.getId() or survey.questions.getTitle()), how would that foreach statement look?
EDIT: SURVEY is a map and not a collection
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>
Basically you need to iterate two times in the loops if your Survey.Question is another collection objects. For example,
<c:foreach items="${survey}" var="survey">
<c:out value="${survey.value}" />
<c:foreach items="${survey.Question" var="question">
$<c:question.item> or $<c:question.title>
</c:foreach>
</c:foreach>