2

Is there any way to execute EL expression received from bean in JSF page?

Bean method

public class Bean {

    public String getExpr() {
        return "#{emtpy row.prop ? row.anotherProp : row.prop}";
    }

}

JSF page:

<p:dataTable value="#{bean.items}" var="row">
    <p:column>
        <h:outputText value="#{bean.expr}" />
    </p:column>
</p:dataTable>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Yegor Koldov
  • 252
  • 1
  • 4
  • 16

2 Answers2

4

Either use JSF Application#evaluateExpressionGet() in getter to programmatically evaluate an EL expression on the current context. This is in this specific case only fishy as you're basically tight-coupling view logic in the controller/model.

public String getExpr() {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().evaluateExpressionGet(context, "#{emtpy row.prop ? row.anotherProp : row.prop}", String.class);
}

Or use JSTL <c:set> (without scope!) in view to create an alias of an EL expression in the view in case your actual concern is the length of the EL expression.

<c:set var="expr" value="#{emtpy row.prop ? row.anotherProp : row.prop}" />

<p:dataTable value="#{bean.items}" var="row">
    <p:column>
        <h:outputText value="#{expr}" />
    </p:column>
</p:dataTable>

Needless to say that JSTL way is way much cleaner.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

Yes there is, but You shouldn't do it in such way.

It should be done on JSF page if it is rendering, or it should be done as java logic in the service class if it is data processing.

It is really bad to do this kind of things (dynamically inject logic during rendering of JSF page), because it will make this code very difficult to maintain. I'm sure that there is better (more straight-forward, expressive and easier to understund for someone else) way of doing what you need.

It is just advice about creating good code, as your question apparently is about doing something that should be kept simple in very complicated way.

Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
  • Main goal of this, is creating dynamic table (remove duplications of tables and logic that used them). I also thinking about wrapping entity with class, where all view specific logic will be kept. But i think there will be some cases, where this bad tricks works well – Yegor Koldov Feb 27 '16 at 11:04
  • It is not clear for me what you wish to do. Please ask another question on stack overflow about how to do this 'creation of dynamic table', post some realted code you have, describe what you would like to achieve. I'am sure there will be plenty of answers how to do this in proper way without dynamic logic injetion into JSF. – Krzysztof Cichocki Feb 27 '16 at 11:13