Understand Flash Scope in JSF2

Ken Chan picture Ken Chan · Jun 25, 2012 · Viewed 40.9k times · Source

From what I understand , objects placed inside the Flash scope in a faces request lifecycle will be available for the next faces request lifecycle and then clear.

Suppose I have two pages:

page01.xhtml:

<h:form>
    <h:commandButton  action="#{page01Bean.action}" />
</h:form>

Page01Bean :

@ManagedBean
@RequestScoped
public class Page01Bean {

        public void action(){
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("fooKey", "fooValue");
        }

}

page02.xhtml:

<h:outputText value="#{flash.fooKey}"/> 

So when the button in page01.xhtml is clicked , a faces request life-cycle (say life-cycle A) starts and set the value to the flash under the key called fooKey

Then I open another browser tab and browse page02.xhtml . Another faces request lifecycle (say lifecycle B) starts to render this page . I expected that lifecycle B can access its previous lifecycle 's flash scope (i.e life-cycle A) and display fooValuein page02.xhtml. However , it displays nothing.

Please correct me what I misunderstand about the flash scope in this exmaple. Thanks so much

Answer

Fritz picture Fritz · Jun 25, 2012

In short, variables stored in the flash scope will survive a redirection and they will be discarded afterwards. This is really useful when implementing a Post-Redirect-Get pattern.

If you try to navigate to another page by redirect and access the attributes on load, they will be there. After that request is done the values in the flash will be discarded. For example:

You're in page1.xhtml and you have a commandLink that redirects to a new page with a method like this one (Note: I'll use implicit navigation).

public String navigateToPageB() {
    FacesContext.getCurrentInstance().getExternalContext().getFlash().put("param1", "Hello World!");
    return "pageB?faces-redirect=true";
}

When pageB.xhtml is rendered, you can access those values by EL expressions such as

<h:outputLabel value="#{flash['param1']}" />

which will display the "Hello World!" string we saved earlier in navigateToPageB.

As for your question, by opening a new tab in your explorer you're not accessing the same context you were accessing on your previous tab, so your variable will not be available there.