使用带有 JSP 的数组

Using arrays with JSP

我有两个对象想合并成一个变量。对象看起来像这样

{name: "James", type: "author"}, {name: "Amelia", type: "author"}

并且可以通过我的 JSP 中的 ${global.content.credits.by} 访问它们。我要做的是列出每个对象的两个名称,这样它们看起来像:James, Amy(列表中最后一项没有尾随逗号)当调用 ${authorNames} 变量时。

我试过以下方法:

<c:forEach items="${global.content.credits.by}" var="author" varStatus="loop">
   <c:set var="authorNames" value="${author.name}" />
</c:forEach>

但我可以显示所有作者姓名的唯一方法是在循环内,在循环外 ${authorNames} 变量在每次迭代时都会被覆盖。

在JSP中是否有某种数组推送方法我可以用来组合两个名称,然后在循环中除了最后一个之外的每个名称之间添加一个逗号。

您可以将名称附加到 authorNames,而不是覆盖它。

<c:forEach items="${global.content.credits.by}" var="author" varStatus="loop">
   <c:if test="${loop.index == 0}>
     <c:set var="authorNames" value="${author.name}" />
   </c:if>
   <c:if test="${loop.index != 0}>
     <c:set var="authorNames" value="${authorNames},${author.name}" />
   </c:if>
</c:forEach>