I am trying to dynamically generate content using JSP.
I have a <c:forEach>
loop within which I dynamically create bean accessors. The skeleton resembles this:
<c:forEach var="type" items="${bean.positionTypes}">
${bean.table} // append 'type' to the "table" property
</c:forEach>
My problem is: I want to change the ${bean.table}
based on the type. For example, if the types were {"Janitor", "Chef}
, I want to produce:
${bean.tableJanitor}
${bean.tableChef}
How can I achieve this?
You can use the brace notation []
to access bean properties using a dynamic key.
${bean[property]}
So, based on your example:
<c:forEach var="type" items="${bean.positionTypes}">
<c:set var="property" value="table${type}" />
${bean[property]}
</c:forEach>
If you need to access a complex field in a dynamic way, you could do this:
<h:outputText value="#{someOtherBean.invokeELGetter('#{bean.'.concat('someProperty.field').concat('}'))}" />
And implement the invokeELGetter in your SomeOtherBean class:
public Object invokeELGetter(String el) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory expressionFactory = facesContext.getApplication().getExpressionFactory();
ValueExpression exp = expressionFactory.createValueExpression(elContext, el, Object.class);
return exp.getValue(elContext);
}
Note that this requires EL 2.2 (Tomcat 7 for those who use Tomcat).
精彩评论