Search code examples
jsfprimefacesjsf-2.2breadcrumbssession-scope

Clear SessionScoped bean when refreshing page


I am using a Bean (MenuBean) to dynamically create a

<p:breadCrumb model="#{menuBean.model}" />  

When transitioning through each page of my application, I push or pop pages from a "page stack", so as to adapt the breadCrumb of each page.

@ManagedBean
@SessionScoped
public class MenuBean implements Serializable {

private MenuModel model;
private int navIdx;
private ArrayList<String[]> pageStack;

@PostConstruct
public void init() {
    pageStack = new ArrayList<>();
    navIdx = 0;
    String [] home = new String[2];
    home[0] = "Home";
    home[1] = "home.xhtml";     
    pageStack.add(home);

    refreshModel();
}

private void refreshModel() {
    model = new DefaultMenuModel();
    int i = 0;
    for(String[] s: pageStack) {
        DefaultMenuItem index = new DefaultMenuItem();
        index.setValue(s[0]);
        index.setCommand("#{menuBean.navigate}");
        index.setParam("index", String.valueOf(i++));
        model.addElement(index);            
    }
}

private void push(String [] page) {
    pageStack.add(page);                
    navIdx++;
    refreshModel();
}

private String pop() {
    pageStack.remove(navIdx--);     
    String[] prevPage = pageStack.get(navIdx);
    refreshModel();

    return prevPage[1];
}

}

In order to maintain this stack, my MenuBean is SessionScoped.
However, when I refresh the last page for example, the initial page is shown (since the url does not change) but the breadCrumb still displays the whole stack.

My question is: Is there a way to clear the MenuBean when the user leaves the page, or refreshes it?


Solution

  • One way you could refresh the bean is using remoteCommand with set auto run on true. So once you refresh the page remote commad will fire and call method in backing bean.

    <!-- init bean on page load -->
    <h:form id="initializePageDataForm">
        <p:remoteCommand name="initializePageDataCommand" autoRun="true" action="#{MenuBean.init()}" />
    </h:form>