Search code examples
jsfjsf-2managed-bean

How to initialize variables in a session scoped bean


I have two booleans that controls the render of some components, the problem is that the variables saves there last state until the session expires, i

<f:facet name="footer">
  <p:commandButton action="#{personBean.report}" ajax="false" value="Publish"
                            rendered="#{personBean.reportMode}" icon="ui-icon-check" />
  <p:commandButton action="#{personBean.saveEditing}" ajax="false" value="Save"
                            rendered="#{personBean.editMode}" icon="ui-icon-check" />
</f:facet>

the bean is session scoped and has the following attributes:

@ManagedBean(name = "personBean")
@SessionScoped
public class ReportPerson {
private boolean editMode;
private boolean reportMode;

}

the bean contains these method that changes the values of the booleans:

public String editPerson() {
    System.err.println("Edit Missing Person");
    editMode = true;
    reportMode = false;
    return "ReportNewPerson";
}

the problem is that these values remains until the session expires and as a result the components renders incorrectly


Solution

  • If you are using a session scoped bean then you should Initialize them in constructor like

    public ReportPerson(){
    //let say you want to show report mode by default
    editMode = false;
    reportMode = true;
    }
    

    after then , create two methods like

    public void inEditMode(){
               editMode = true;
               reportMode = false;
    }
    
    public void inReportMode(){
               editMode = false;
               reportMode = true;
    }
    


    Now call #{reportPerson.editMode} and #{reportPerson.reportMode} on your rendering cpomponent and call these methods inReportMode() and inEditMode by getting bean from sessionmap in your backing bean.You may get bean from sessionmap like this

    ReportPerson rp = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("reportPerson");
    

    From this , you can get current bean and from this you can invoke

    rp.inEditMode();
    


    As by using session scope , you have to change them by your logic because they will keep their state remain during the whole session.