This question already has an answer here:
How to get value of bean property when property name itself is a dynamic variable

(1个答案)


5年前关闭。




我正在尝试使用JSP动态生成内容。

我有一个<c:forEach>循环,可以在其中动态创建bean访问器。骨架类似于:
<c:forEach var="type" items="${bean.positionTypes}">
    ${bean.table}  // append 'type' to the "table" property
</c:forEach>

我的问题是:我想根据类型更改${bean.table}。例如,如果类型是{"Janitor", "Chef},我想产生:
${bean.tableJanitor}
${bean.tableChef}

我怎样才能做到这一点?

最佳答案

您可以使用大括号表示法[]通过动态键访问bean属性。

${bean[property]}

因此,根据您的示例:
<c:forEach var="type" items="${bean.positionTypes}">
    <c:set var="property" value="table${type}" />
    ${bean[property]}
</c:forEach>

09-10 09:00
查看更多