在 JSF 中访问静态 属性

Access static property in JSF

我的一个支持 bean 中有一个包含 Select 个项目的静态列表:

private static List<SelectItem> countries = new ArrayList<SelectItem>();

具有以下 getter 和 setter:

public static List<SelectItem> getCountries()     {
    return countries;
}

public static void setCountries(List<SelectItem> countries) {
    LoadSelectItemsBean.countries = countries;
}

我在通过 XHTML 页面访问静态列表时遇到问题。我试过的代码如下:

<ace:simpleSelectOneMenu id="countryField"
   value="#{generalCarrierDataViewBean.carrierBean.countryId}">
   <f:selectItems value="#{loadSelectItemsBean.countries}" />
   <ace:ajax />
</ace:simpleSelectOneMenu>

问题行是:

 <f:selectItems value="#{loadSelectItemsBean.countries}" />

产生的异常是:

javax.el.PropertyNotFoundException: /pages/GeneralCarrierData.xhtml @394,64 value="#{loadSelectItemsBean.states}": Property 'states' not found on type com.oag.reference.util.LoadSelectItemsBean

有人可以建议如何从辅助 bean 中正确引用静态 属性 吗?

谢谢

根据定义,属性不是 static。所以 getters 和 setters 不能简单地是静态的,尽管它们反过来可以引用静态变量。但是外界看不到。

您有 3 个选择:

  1. 从 getter 中删除 static 修饰符。整个setter是不必要的,你可以删除它。

    public List<SelectItem> getCountries()     {
        return countries;
    }
    
  2. 如果你真的坚持访问静态"properties"(函数),就创建一个EL函数。可以在这个答案中找到详细信息:How to create a custom EL function to invoke a static method?

  3. 将整个 List<SelectItem> 变成一个 enum 并利用 OmniFaces <o:importConstants>. Detail can be found in this answer: How to create and use a generic bean for enums in f:selectItems?

只需创建一个非静态方法 returns 静态 属性:

// here you have a static String
private static String static_str;

public static String getStatic_str() {
    return static_str;
}

// in jsf page: #{myClass.str}
public String getStr() {
    return static_str;
}