从JSF传递枚举值作为参数(重访)

3

JSF中将枚举值作为参数传递

这个问题已经涉及到了这个问题,但是提出的解决方案对我没有用。我在我的后端bean中定义了以下枚举:

public enum QueryScope {
  SUBMITTED("Submitted by me"), ASSIGNED("Assigned to me"), ALL("All items");

  private final String description;

  public String getDescription() {
    return description;
  }

  QueryScope(String description) {
    this.description = description;
  }
}

然后我将其用作方法参数。

public void test(QueryScope scope) {
  // do something
}

并且可以通过EL在我的JSF页面中使用它

<h:commandButton
      id        = "commandButton_test"
      value     = "Testing enumerations"
      action    = "#{backingBean.test('SUBMITTED')}" />

到目前为止一切顺利——与原问题中提出的问题相同。然而,我必须处理一个javax.servlet.ServletException: Method not found: %fully_qualified_package_name%.BackingBean.test(java.lang.String)

因此,似乎JSF正在解释方法调用,好像我想调用一个具有字符串作为参数类型的方法(当然不存在),因此没有进行隐式转换。

这个示例与上述链接的行为不同的因素是什么?


你的BackingBean实例中是否有QueryScope的实例?我无法看到你整个BackingBean类,但我可以想象这可能是JSF无法注册枚举类型的原因。 - youri
enum 定义是 BackingBean 类的一部分。它本身没有作为成员的 QueryScope 实例。 - Simon Voggeneder
1个回答

5
在您的backingBean中,您可能编写了一个带有enum参数的方法:
<!-- This won't work, EL doesn't support Enum: -->
<h:commandButton ... action="#{backingBean.test(QueryScope.SUBMITTED)}" />

// backingBean:
public void test(QueryScope queryScope) {
    // your impl
}

然而,提议的解决方案并没有使用枚举,而是使用了String。这是因为EL根本不支持枚举:

<!-- This will work, EL does support String: -->
<h:commandButton ... action="#{backingBean.test('SUBMITTED')}" />    

// backingBean:
public void test(String queryScopeString) {
    QueryScope queryScope = QueryScope.valueOf(queryScopeString);
    // your impl
}

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