如何为HtmlCommandLink创建操作#setActionExpression()

Pal*_*avi 3 jsf-2

我试图以编程方式添加commandlink,但我无法添加操作.

HtmlCommandLink link = new HtmlCommandLink();
link.setValue(data);
link.setActionExpression(no idea);
Run Code Online (Sandbox Code Playgroud)

我该如何创建它?

Bal*_*usC 5

使用ExpressionFactory#createMethodExpression().

这是一个方便的方法:

private static MethodExpression createMethodExpression(String expression, Class<?> returnType) {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().getExpressionFactory().createMethodExpression(
        context.getELContext(), expression, returnType, new Class[0]);
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它,前提是您public String doSomething() {}在托管bean中执行了以下操作#{bean}:

link.setActionExpression(createMethodExpression("#{bean.doSomething}", String.class));
Run Code Online (Sandbox Code Playgroud)