如何评估JSF复合组件中的MethodExpressions

4

我不确定在组合组件中处理方法表达式的“正确”方式。

我的组合组件使用一个支持类来执行动作方法。这些方法执行一些默认操作或将传递给组合组件用户作为属性的动作方法委托:

在页面中使用:

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

组合模式:

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

后备类:

@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;

}

}

上述代码按预期工作,但我觉得它相当臃肿,并且它创建一个ValueExpression来从声明的“action”属性中检索方法表达式。

UIComponentBase提供了getValueExpression("attributeName"),但是没有类似于MethodExpressions的东西。

因此,我的问题是,是否有比上面的代码更好的方法来评估在组合组件中声明为属性的MethodExpressions

谢谢。

1个回答

4

将其作为属性而不是值表达式获取。

因此,不要写成

ValueExpression ve = getValueExpression("action");

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

谢谢你的快速回复。我想我会坚持使用臃肿的代码,因为我的组件包含多个命令按钮和数据表格,所以从UICommand继承可能会产生歧义。但这是另一个问题类的不错解决方案。 - Darkspirit
理论上来说,你不需要这样做。无论组合中有多少个命令按钮,只有一个MethodExpression,即当前调用的方法表达式。 - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接