【问题标题】:JSF - Loading UISelectItem list in constructorJSF - 在构造函数中加载 UISelectItem 列表
【发布时间】:2011-01-12 18:41:58
【问题描述】:

我正在使用 JSF2.0 和 Primefaces 2.2RC2 运行应用程序

我已经在我的项目上运行了分析器,并确定存在来自 UISelectItems 列表的瓶颈。该列表在我的应用程序中的每个操作中被填充了 6 次。

UISelectItem 列表被填充到名为 getCountryList() 的 getter 方法中,它看起来像这样

public UISelectItems getCountryList() throws Exception {
    Collection List = new ArrayList();
    List<Countries> c_list = myDao.getCountryList();

    for( QcardCountries c : c_list ) {
       list.add(new SelectItem(c.getCountryId().toString(), c.getCountryName());
    }

    UISelectItems countries = new UISelectItems();
    countries.setValue(list);
    return countries;
}

当我像这样调用视图时这有效

<f:selectItems binding="#{myBean.countryList}" />

但对于我在应用程序中所做的每个按钮或操作,它再次被调用 6 次。

然后我尝试将 List 的创建移动到在 @PostContruct 上调用的方法中,但是当我这样做时,列表在我使用时不会显示

 <f:selectItems binding="#{myBean.countryList}" /> 

它只是显示为空。有谁知道如何正确创建一个列表,以便它只创建一次,并且可以在整个用户会话中调用以填充下拉列表?

【问题讨论】:

    标签: java jsf jsf-2 primefaces


    【解决方案1】:

    org.life.java 已经给出了有关加载的提示,但是由于您不必要地使用 binding 并且 JSF 2.0 提供了一种将 List&lt;SomeBean&gt; 而不是 List&lt;SelectItem&gt; 作为值的方法,这里有一个完整的示例如何以正确的方式做到这一点:

    private List<Country> countries;
    
    @PostConstruct
    public void init() {
        countries = myDao.getCountryList();
    }
    
    public List<Country> getCountries() {
        return countries;
    }
    

    <f:selectItems value="#{bean.countries}" var="country" itemValue="#{country.id}" itemLabel="#{country.name}" />
    

    (请注意,我将 Countries 模型重命名为 Country 并将 getCountryId() 重命名为 getId() 并将 getCountryName() 重命名为 getName(),因为这样更有意义)

    另见:

    【讨论】:

    • 啊,我一直都做错了。谢谢这很好用,我的应用程序快了 20 倍。
    【解决方案2】:

    在类的字段中取出列表,在@postconstruct中初始化,在get方法中检查它的null是否创建并返回,否则返回,

    【讨论】:

    • 正确,但不需要在 getter 中进行 nullcheck。
    • 所以我把 List c_list = myDao.getCountryList();在我的@PostConstruct 中?我很困惑我应该在那里加载什么
    • 是的,你是对的,只是在类字段中列出,如@BalusC所示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2013-09-04
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多