I had problems when building a JSF project with ViewScope
ManagedBeans
. So I decided to isolate the problem to a simple code where obviously the problem persists.
Basically I realized that the properties that are in the class TesteMBean
work perfectly, however, the properties inherited from the superclass GenericoMBean
not preserve its value.
I'm still beginner to it and so do not know if this is normal behavior of the JSF. Can someone enlighten me on this? and if possible tell me how to do it right through an example. thank you very much.
Following the code.
The SuperClass:
package br.com.telesnet.sige.web.mb;
public abstract class GenericoTesteMBean {
protected String textoBase;
public java.lang.String getTextoBase() {
if (this.textoBase == null){
return "";
}else{
return textoBase;
}
}
public void setTextoBase(String textoBase) {
this.textoBase = textoBase;
}
}
The Inherited ManagedBean:
package br.com.telesnet.sige.web.testes;
import java.io.Serializable;
import javax.annotation.ManagedBean;
import javax.faces.bean.ViewScoped;
import br.com.telesnet.sige.web.mb.GenericoTesteMBean;
@ManagedBean
@ViewScoped
public class TesteMBean extends GenericoTesteMBean implements Serializable{
private static final long serialVersionUID = 1L;
private java.lang.Integer valor;
private java.lang.String texto;
public TesteMBean(){
this.setValor(0);
}
public void incrementar(){
this.setValor(this.getValor()+1);
this.texto = this.getTexto() + "X";
this.textoBase = this.getTextoBase() + "A";
}
public java.lang.Integer getValor() {
if (this.valor == null){
return 0;
}else{
return valor;
}
}
public void setValor(java.lang.Integer valor) {
this.valor = valor;
}
public java.lang.String getTexto() {
if (this.texto == null){
return "";
}else{
return texto;
}
}
public void setTexto(java.lang.String texto) {
this.texto = texto;
}
}
The Web form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<f:view>
<h:form id="formLabel">
<h:outputLabel value="Valor:"></h:outputLabel>
<h:outputLabel value="#{testeMBean.valor}"></h:outputLabel>
<h:outputLabel value="Texto:"></h:outputLabel>
<h:outputLabel value="#{testeMBean.texto}"></h:outputLabel>
<h:outputLabel value="TextoBase:"></h:outputLabel>
<h:outputLabel value="#{testeMBean.textoBase}"></h:outputLabel>
</h:form>
<h:form id="formIncremento">
<h:commandButton actionListener="#{testeMBean.incrementar()}" value="incrementar">
</h:commandButton>
</h:form>
</f:view>
</h:body>
</html>
The output undesired (Button "incrementar" clicked five times):
Valor: 5 Texto: XXXXX TextoBase: A
The required output (Button "incrementar" clicked five times):
Valor: 5 Texto: XXXXX TextoBase: AAAAA