Sunday, September 26, 2010

Flash scope in JSF 2.0 (nothing about Adobe Flash)

In JSF 2.0, amongst Request, Session etc, there is the new scope called Flash. (However there is no annotation @FlashScope, and you can't put bean in this scope). It's concept is taken from Ruby on Rails. Data in Flash scope are available for current and for next request, but not for subsequent requests. Usage is very simple.
On first page (e.g. index.html):
<h:form>
  <h:inputtext value="#{flash.text}">
  <h:commandbutton action="page?faces-redirect=true" value="To page">
</h:form>
And this is the page we are redirecting to, page.xhtml:
<h:form>
  <h:outputtext value="#{flash.text}">
</h:form>
Why would you need such scope? Imagine you want to enter data on one page, then redirect to another page, and display this data. If not for redirect, we could use Request scope. But with redirect value is sent with request, then browser is redirected to another page, and makes another request. Request scoped value is gone. In such case Flash scope becomes useful. We can put value in this scope with one request, and when another request is made, the value is still there. But it is not stored in session, and is not available for subsequent requests.

However, there is a way to make data in Flash scope alive a bit longer. It is enough if in page.xhtml we change #{flash.text} to #{flash.keep.text}. This way data is not removed from the scope after first request, but is available for one more.

In managed beans, you can get flash scope by
Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();