5

我有一个模板,它是编辑某些元素的表单的一部分。要执行的操作因包含它的页面而异。所以我将action方法作为参数传递:

 <ui:param name="option" value="#{someOptionBean}" />
 ...
 <ui:include src="/WEB-INF/jsf/value-edit.xhtml">
    <ui:param name="controllerParam" value="#{optionController}" />
    <ui:param name="elementParam" value="#{option}" />
    <ui:param name="actionParam" value="updateOption" />
 </ui:include>

或者:

 <ui:param name="property" value="#{somePropertyBean}" />
 ...
 <ui:include src="/WEB-INF/jsf/value-edit.xhtml">
    <ui:param name="controllerParam" value="#{propertyController}" />
    <ui:param name="elementParam" value="#{property}" />
    <ui:param name="actionParam" value="updateProperty" />
 </ui:include>

里面value-edit.xhtml有一个命令按钮:

<p:commandButton value="Update" action="#{controllerParam[actionParam](elementParam)}" />

到目前为止一切正常。

我的问题是现在动作方法没有相同数量的参数。他们是:

public void updateOption(Option option) { ... }
public void updateProperty(Item item, Prop property) { ... }

所以我现在希望能够将动作参数定义为:

<ui:param name="actionParam" value="updateOption(option)" />
<ui:param name="actionParam" value="updateProperty(item, property)" />

或类似的东西:

<ui:param name="method" value="updateProperty" />
<ui:param name="parameters" value="item, property" />

我已经阅读了文档(值和方法表达式/参数化方法调用),但我不确定这是否可能。

有什么办法可以做到这一点?

4

1 回答 1

5

最后我解决了这个MethodExpression在控制器中创建

现在ui:include看起来像:

<ui:param name="option" value="#{someOptionBean}" />
...
<ui:include src="/WEB-INF/jsf/value-edit.xhtml">
    <ui:param name="actionParam" value="#{optionController.getUpdateAction()}" />
</ui:include>

<ui:param name="item" value="#{someItemBean}" />
<ui:param name="property" value="#{somePropertyBean}" />
...
<ui:include src="/WEB-INF/jsf/value-edit.xhtml">
    <ui:param name="actionParam" value="#{propertyController.getUpdateAction()}" />
</ui:include>

value-edit.xhtml命令按钮中是:

<p:commandButton value="Update" action="#{actionParam}" />

为每个控制器getUpdateAction创建MethodExpression具有相应参数的 :

public class OptionController {
    ...
    public void updateOption(Option option) { ... } 

    public MethodExpression getUpdateAction() {
        return createMethodExpression("#{optionController.updateOption(option)}", String.class, Option.class);
    }
    ...
}

public class PropertyController {
    ...
    public void updateProperty(Item item, Prop property) { ... }

    public MethodExpression getUpdateAction() {
        return createMethodExpression("#{propertyController.updateProperty(item, property)}", String.class, Item.class, Prop.class);
    }
    ...
}

哪里createMethodExpression是:

public static MethodExpression createMethodExpression(String expression, Class<?> expectedReturnType, Class<?>... expectedParameterTypes) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    return facesContext.getApplication().getExpressionFactory().createMethodExpression(
        facesContext.getELContext(), expression, expectedReturnType, expectedParameterTypes);
}
于 2015-02-20T16:48:49.757 回答