6

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
bulk
  • 83
  • 1
  • 6

2 Answers2

13

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>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    This works for a property. What about a property inside a property (i.e., bean.someProperty.someField)? I did manage to get that to work, but I am not sure if my solution follows the best practices. @BalusC is my solution (see my answer below) alright or is there a best way to do this? – Andre Aug 20 '12 at 14:15
0

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).

Andre
  • 3,874
  • 3
  • 35
  • 50