In JSF, data can be retrieved in a facelet ( .xhtml
file) or even in a JSP by simply calling the getter methods of JSF beans.
It is not necessary to create elaborate expression languages , simply delegate the required logic to getter .
One point to consider is that there is no guarantee that an getter will be called only once. If the code executed in the getter has some cost, for example reading in the database, one must "cache" the value in an attribute of the bean.
Example:
private List<Classe> list;
public String getListClasses() {
if (list == null) {
list = dao.listaClassesDoBanco();
}
return list;
}
And, in the case of an operation that searches for an attribute, depending on the cost, you could also create a map whose key is the value of the attribute.
In addition, if the list does not change on the screen it should be loaded only once. This can be done as in the above method or even in a method annotated with @PostConstruct
, which is called whenever the bean is re-created in its proper scope.
Example:
public class ManagedBean {
private List<Classe> list = new ArrayList<Classe>();
private Map<String, Classe> mapaClasse;
@PostConstruct
public void init() {
list = dao.listaClassesDoBanco();
}
private Map<String, Classe> getMapaClasse() {
if (mapaClasse == null) {
mapaClasse = new HashMap<String, Classe>();
for (Classe c : list) {
mapaClasse.put(c.tipoConteudo, c);
}
}
return mapaClasse;
}
public Classe getObjetoAzul() {
return getMapaClasse().get("azul");
}
...
}
The expression on your facelet looks like this:
#{managedBean.objetoFinal.objetoAzul}
You can also access the map value directly:
#{managedBean.mapaClasse.azul}
Or:
#{managedBean.mapaClasse['azul']}
If you are using EL 2.2, you can still do this:
public Classe getObjetoPorTipoConteudo(String tipoConteudo) {
return getMapaClasse().get(tipoConteudo);
}
And use the expression:
#{managedBean.getObjetoPorTipoConteudo('azul')}