在Java中创建MethodExpression(并在JSF中使用)

时间:2016-08-01 16:11:51

标签: jsf richfaces el uiinclude methodexpression

我一直在尝试使用具有自动完成功能的“通用”对话框,现在可以使用几天。事实证明,我只是以“错误的方式”创建了MethodExpression。所以我想我会在这里记录下来。

重申:您希望动态创建MethodExpression,将其存储在Property中并在JSTL Template或JSF Page中使用它。

例如:

// Template
<c:forEach items="#{property.subItems}" var="subitem">
  <ui:include src="editor.xhtml">
    <ui:param name="autocompleteMethod" value="#{subitem.autocompMethod}" />
  </ui:include>
</c:forEach>

// editor.xhtml
// We're using RichFaces (unfortunately), but this is just an example
<rich:autocomplete mode="cachedAjax" minChars="2"
      autocompleteMethod="#{autocompleteMethod}"
/>

1 个答案:

答案 0 :(得分:0)

我在http://javaevangelist.blogspot.co.at/2012/10/jsf-2x-tip-of-day-programmatically_20.html

找到了解决方案
public static MethodExpression createMethodExpression(String methodExpression, Class<?> expectedReturnType, Class<?>[] expectedParamTypes) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory()
            .createMethodExpression(context.getELContext(), methodExpression, expectedReturnType, expectedParamTypes);
}

然后,您可以创建一个MethodExpression并将其存储在属性中。对于RichFaces自动填充,签名为:List<String> autocomplete(String prefix)

@SuppressWarnings("rawtypes") // Generics use type erasure
Class<List> retType = List.class;
Class<?>[] paramTypes = {String.class};
MethodExpression autocompleteMethod = createMethodExpression("#{myBean.myAutocomplete}", retType, paramTypes);
// In the questions example, we'd need to set a property here:
this.autocompMethod = autocompleteMethod;

然后有适当的吸气剂:

MethodExpression getAutocompMethod() {
    return this.autocompMethod;
}