JSF - Loading UISelectItem list in constructor
-
10-10-2019 - |
문제
I am running an application using JSF2.0 and Primefaces 2.2RC2
I have run the profiler on my project and determined there was a bottleneck coming from a UISelectItems list. The list was being populated like 6 times on each action in my application.
The UISelectItem list was being populated in a getter method called getCountryList() and it looked like this
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;
}
This works when I call in the views like so
<f:selectItems binding="#{myBean.countryList}" />
but again it is called like 6 times for each button or action I make in the application.
I then attempted to move the creation of the List into a method that was called on @PostContruct but when I do that the list does not show up when I use
<f:selectItems binding="#{myBean.countryList}" />
It just shows up as empty. Does anyone know how to properly create a list so it is only created one time and can be called throughout an entire users session to populate a dropdown list?
해결책
org.life.java already gave a hint about loading, but since you're unnecessarily using binding
and JSF 2.0 provides a way to just take List<SomeBean>
instead of List<SelectItem>
as value, here's a complete example how to do it the right way:
private List<Country> countries;
@PostConstruct
public void init() {
countries = myDao.getCountryList();
}
public List<Country> getCountries() {
return countries;
}
with
<f:selectItems value="#{bean.countries}" var="country" itemValue="#{country.id}" itemLabel="#{country.name}" />
(note that I renamed Countries
model to Country
and getCountryId()
to getId()
and getCountryName()
to getName()
since that makes more sense)
See also:
다른 팁
take list out at class's field , initialize it in @postconstruct
, in get method check if its null create it and return it or else return it,