在 JSTL 循环中使用 JSTL 变量

Use JSTL variable in the JSTL loop

我需要在嵌套循环中访问 JSTL 中的两个依赖 ArrayList。首先,我迭代一个 String 类型的 ArrayList,然后循环中的值将用于访问另一个 ArrayList。

<c:forEach items="${productCatagoryList}" var="category">
    <c:forEach items=${${category}} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>

在第一个 foreach 循环中,我将获取类别作为字符串值,对于所有这些类别,还有另一个包含一些产品的 ArrayList。

因此,第一个循环中的每个字符串值都将用于第二个 foreach 循环。

第二行代码出错。如何在第二个循环ans items中使用第一个循环的结果?

您可以在同一个 class 中创建一个带有参数 category 的方法。应该是字符串类型。然后你可以从 EL 中调用这个方法。较新的 EL 允许调用您可以使用的方法而不是自定义函数。

<c:forEach items="${productCategoryList}" var="category">
    <c:forEach items=${getProductsForCategory(category)} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>

如果您像这样将类别映射到产品

Map<String, List<Product>> productCategory;

那么你可以简单地为这个变量使用一个getter

<c:forEach items="${productCategoryList}" var="category">
    <c:forEach items=${productCategory[category]} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>