0
  • 我正在通过 java 代码直接构建 MethodExpression。
  • 它将表示对带有参数(如 follow)的 bean 方法的调用。
#{bean.method(TheObjectInstance)}
  • 该对象是一个简单的自定义 pojo 对象
public class TheObject
{
   public String value0 = "value0";
}
  • 我们现在创建 MethodExpression,如下所示。
    TheObject object = new TheObject();

    FacesContext context = FacesContext.getCurrentInstance();
    Application application = context.getApplication();
    ExpressionFactory factory = application.getExpressionFactory();

    //Create method expression
    MethodExpression methodExpression = factory.createMethodExpression(
       context.getELContext(), 
       "#{bean.method(" + object + ")}", 
       null, 
       new Class<?>[] {TheObject.class});
  • 它会生成以下错误。
javax.servlet.ServletException: Encountered "@" at line 1, column 87.
Was expecting one of:
    "." ...
    "(" ...
    ")" ...
    "[" ...
    "," ...
    ";" ...
    ">" ...
    "gt" ...
    "<" ...
    "lt" ...
    ">=" ...
    "ge" ...
    "<=" ...
    "le" ...
    "==" ...
    "eq" ...
    "!=" ...
    "ne" ...
    "&&" ...
    "and" ...
    "||" ...
    "or" ...
    "*" ...
    "+" ...
    "-" ...
    "?" ...
    "/" ...
    "div" ...
    "%" ...
    "mod" ...
    "+=" ...
    "=" ...
  • 我尝试了使用字符串作为参数和布尔对象的相同代码,它工作正常,但使用自定义对象会产生相同的错误,以及如果我们传递一个复杂对象(例如 UIComponent)。

  • 我正在使用 JSF 2.2,欢迎提供任何帮助。

4

1 回答 1

0
  • 要使用包含对象作为参数的 bean 方法创建 MethodExpression #{bean.method(object)},我们应该使用在 HTML 页面中声明的 var 的名称var=object
    <h:form>
     <h:datatable var="object" value="#{bean.objects}">
      <h:commandbutton value="test" actionlistenner="#{bean.method(object)}"/>
    </h:datatable>
    </h:form>
  • 如果我们想生成相同的 MethodExpression #{bean.method(object)},我们将必须生成完整的 html 元素,包括在我们的例子中的父 html 元素一个包含对象引用的数据表,var=object然后在 MethodExpression 的代码中
    //Wrong implementation: the object is converted as object.getClass().toString()
    MethodExpression methodExpression = factory.createMethodExpression(
       context.getELContext(), 
       "#{bean.method(" + object + ")}", 
       null, 
       new Class<?>[] {TheObject.class});

    //Right implementation: we refer to object referenced by the datatable var. 
    MethodExpression methodExpression = factory.createMethodExpression(
       context.getELContext(), 
       "#{bean.method(object)}", 
       null, 
       new Class<?>[] {TheObject.class});
于 2019-05-17T21:35:17.417 回答