2
votes

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>
2
For my purpose, i've decide to wrapping entity with another class, where all view specific logic evaluated - Yegor Koldov

2 Answers

4
votes

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:

2
votes

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.