在JSF中访问静态属性

7

我有一个静态的选择项列表在我的其中一个后端bean中:

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中正确引用静态属性?

谢谢。

2个回答

15

根据定义,属性不是静态的。因此,getter和setter不能是静态的,尽管它们可以引用静态变量。但外部世界看不到这一点。

您有3个选项:

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

    public List<SelectItem> getCountries()     {
        return countries;
    }
    
  2. 如果您真的坚持要访问静态 "属性"(函数),则可以创建 EL 函数。有关详细信息,请参阅此答案:如何创建自定义 EL 函数以调用静态方法?

  3. 将整个 List<SelectItem> 转换为 enum 并利用 OmniFaces 的 <o:importConstants>。有关详细信息,请参阅此答案:如何为 f:selectItems 创建和使用通用枚举 bean?


谢谢,我可能会选择第一种选项,并将我的bean更改为之前配置的方式。 - LiamWilson94

0

只需创建一个非静态方法,该方法返回静态属性:

// 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;
}

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