In JSF, data can be recovered in a facelet (file .xhtml
) or even in a JSP through simple method calls getter by Mr JSF.
No need to create Expression Languages elaborated, it is sufficient to delegate the necessary logic to the getter of Managed Bean.
One point to be considered is that there is no guarantee that a getter will be called only once. If the code executed in getter has some cost, for example reading in the database, one must "cachear" the value in a bean attribute.
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, one could also create a map whose key is the value of the attribute.
Also, if the list is not changed on the screen it should be loaded only once. This can be done as in the above method or in an annotated method with @PostConstruct
, which is called whenever the bean is recreated 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')}
You cannot make a method with your search code and then use it on the other page?
– lionbtt
Why should it be on a line? What does this requirement have to do with JSF?
– Miguel Cartagena
I would recommend a functional approach.
– Beterraba
@Miguelcartagena probably because he is wanting to use this in an expression (e.g..:
${ ... }
) that must return a value.– mgibsonbr
@mgibsonbr if that’s the case, Fábio’s solution is perfect.
– Miguel Cartagena