JSTL打印嵌套对象 [英] JSTL Printing Nested Objects
问题描述
如何在JSP页面的地图中打印嵌套对象/属性的值?
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>
所以让我们说Survey有一个名为Questions(这是另一个对象)的属性,我想打印问题(survey.questions.getId()或survey.questions.getTitle()),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?
编辑:SURVEY是一个地图而不是收集
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>
假设您收集了 Survey
对象绑定到调查
属性,每个调查
有一个标题。它将打印每个调查的标题。
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.
如果您的嵌套属性是对象的集合,那么您可以使用 forEach
循环来迭代它们,就像在你的例子中
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>
这将打印每个问题的标题
假设您有一个绑定到调查
属性的调查对象,而
调查
对象具有问题
对象作为一个字段的集合(使用适当的getter方法,即 getQuestions()
)。
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>
这篇关于JSTL打印嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!