我正在尝试做一些看起来应该相对简单但有点碰壁的事情。
假设我有一个产品列表,我将其公开为名称 products
下的请求属性.我们还假设每个产品都有一个 id
字段,而且我还有一堆以 selectedProduct_<product-id>
形式设置的请求属性以指示选择了哪些。
我知道有更好的方法来表示此信息,例如将所有选定的 ID 放入 Map
中并对此进行检查,但让我们假设我出于任何原因无法访问该方法。
所以我想做的是迭代products
并仅在存在 selectedProduct_...
时发出一些标记当前产品的属性集。像这样的东西:
<c:forEach var="product" items="${products}">
<c:if test="${! empty selectedProduct_${product.id}}">
<div class="productId">${product.id}</div>
</c:if>
</c:forEach>
但这当然行不通,因为它死于 ${! empty selectedProduct_${product.id}}
.
如果我将产品 ID 硬编码到表达式中,将会起作用,例如:
${! empty selectedProduct_17}
...假设“17”是有效的产品 ID。显然这不切实际,但希望它能说明我正在努力实现的目标。基本上我需要:
- 确定正确的
selectedProduct_...
forEach
中每次迭代使用的值环形。像<c:set var="key" value="selectedProduct_${product.id}"/>
这样简单的东西会这样做,除非我不确定如何然后采取key
并使用它来获取具有该名称的请求属性的值(不作弊并在<% %>
block 内运行文字 Java 代码)。 - 获取我在#1 中确定其名称的请求属性的值。这似乎是棘手的部分。
这可能使用纯 JSP/JSTL 吗?我知道我可以在 <% %>
中运行一些 Java 代码解决这个问题,但这似乎是非常糟糕的形式。当然存在更优雅的解决方案?
最佳答案
您可以使用 implicit objects :
There are objects that allow access to the various scoped variables described in Using Scope Objects.
When an expression references one of these objects by name, the appropriate object is returned instead of the corresponding attribute. For example, ${pageContext} returns the PageContext object, even if there is an existing pageContext attribute containing some other value.
- pageScope: Maps page-scoped variable names to their values
- requestScope: Maps request-scoped variable names to their values
- sessionScope: Maps session-scoped variable names to their values
- applicationScope: Maps application-scoped variable names to their values
所以,例如:
<c:set var="selectedProductAttrName" value="selectedProduct_${product.id}"/>
${requestScope[selectedProductAttrName]}
关于java - JSP 表达式语言和动态属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12401034/