繁体   English   中英

JSF - 在构造函数中加载UISelectItem列表

[英]JSF - Loading UISelectItem list in constructor

我正在使用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}" /> 

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

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

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

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模式CountrygetCountryId()getId()getCountryName()getName()因为这更有意义)

也可以看看:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM