How to evaluate MethodExpressions in JSF composite components

点点圈 提交于 2019-12-22 08:55:04

问题


I am not sure about the "correct" way to deal with method expressions in composite components.

My composite uses a backing class with action methods. Theses perform some default actions or delegate to an action method passed by the composite user as an attribute:

In using page:

<my:component action="#{myBean.actionMethod}" />

Composite:

<cc:interface componentType="mycomponentType">
  <cc:attribute name="action" method-signature="java.lang.String action()" required="false" />
</cc:interface>

<cc:implementation>
  <h:commandButton value="submit" action="#{cc.componentAction}" />
</cc:implementation>

Backing class:

@FacesComponent("mycomponentType")
public class UIMyComponent extends UINamingContainer {   

public String action() {
    String outcome = "";

    ValueExpression ve = getValueExpression("action");
    String expression = ve.getExpressionString();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    Application application = facesContext.getApplication();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory = application .getExpressionFactory();

    MethodExpression methodExpression = expressionFactory.createMethodExpression(elContext, expression, String.class, new Class[0]);

    outcome = (String) methodExpression.invoke(elContext, new Object[0]);

    if (outcome.equals("whatever")) {
        // set another outcome
    }


    return outcome;

}

}

The code above is working as expected, but I find it rather bulky and it creates a ValueExpression to retrieve the method-expression from the declared "action" attribute.

UIComponentBase offers getValueExpression("attributeName") but there is nothing similar for MethodExpressions.

So my Question is if there is a better way to evaluate MethodExpressions declared as attributes in composite components than the code above.

Thx


回答1:


Get it as attribute instead of as value expression.

So, instead of

ValueExpression ve = getValueExpression("action");

do

MethodExpression me = (MethodExpression) getAttribute("action");


来源:https://stackoverflow.com/questions/8532697/how-to-evaluate-methodexpressions-in-jsf-composite-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!