Search code examples
jsf-2primefacesscopemanaged-beanbrowser-tab

How to reset session scoped bean when re-opening page in new browser tab


Once the tab on the xhtml page (primefaces) is closed after submitted the values, I re-open a new tab which selects the same bean the old values are still there. I'd like to open a new tab with the default values (new instance of the backing bean).

XHTML page

<h:form>
    <p:layout style="min-width:400px;min-height:700px" >
        <p:layoutUnit position="west" style="min-width:200px;min-height:50px">

            <ui:include src="Menu.xhtml" />


        </p:layoutUnit>

        <p:layoutUnit  position="center" >
            <p style="text-align:center">Welcome</p>

            <p:tabView dynamic="false" widgetVar="tabView">
                <p:ajax event="tabClose" listener="#{requestCalculation.onTabClosed}"/>
                <c:forEach items="#{requestCalculation.formTabs}" var="listItem">
                    <p:tab title="#{listItem.formTitle}"  closable="true" >
                        <ui:include src="#{listItem.formPage}" />
                     </p:tab>
                </c:forEach>

            </p:tabView>
                <h:panelGrid columns="2">
                    <h:commandButton value="Calculate" action = "#{requestCalculation.calculate}"/>
                    <h:commandButton value="Reset" action = "#{requestCalculation.resetPage}"/>
                </h:panelGrid>
        </p:layoutUnit>

    </p:layout>

</h:form>


Backing Bean

public String loadForm(TcsBase loadForm){

    id = loadForm.getId();

    ViewTabs tab = new ViewTabs();
    tab.setFormTitle("Form".concat(id));
    tab.setFormPage("Form".concat(id).concat(".xhtml"));
    formTabs.add(tab);  

    calcReq.getFormCollection().add(loadForm);

    System.out.println(loadForm.getId());
    return "Main";
}

public void onTabClosed(TabCloseEvent e){
    TabView tabView = (TabView) e.getComponent();
   int closingTabIndex = tabView.getChildren().indexOf(e.getTab());
   removeForm(closingTabIndex);

}

public void removeForm(int index){
    calcReq.getFormCollection().remove(index);
    formTabs.remove(index);

}


Solution

  • As the bean appears to hold view scoped data (the view scope lives as long as you're postbacking in the same browser window/tab), you should make it @ViewScoped, not @SessionScoped. This way you also don't need to mess around with manually creating and destroying beans. Just put the bean in the right scope in first place.

    See also: