RoR Flash Scope in JSF-2

21 Oct
2009

While browsing through the Mojarra Sourcecode, I’ve found a interesting set of classes, all bundled around the keyword “Flash”:

./jsf-ri/systest/src/com/sun/faces/systest/FlashViewParamTestCase.java
./jsf-ri/systest/src/com/sun/faces/systest/FlashReaperTestCase.java
./jsf-ri/systest/src/com/sun/faces/systest/FlashReaperBean.java
./jsf-ri/systest/web/flash01.xhtml
./jsf-ri/systest/web/flash02.xhtml
./jsf-ri/systest/web/flashReaper.xhtml
./jsf-ri/src/com/sun/faces/context/flash
./jsf-ri/src/com/sun/faces/context/flash/FlashELResolver.java
./jsf-ri/src/com/sun/faces/context/flash/ELFlash.java
./jsf-ri/systest-per-webapp/flash/src/java/com/sun/faces/systest/FlashTestCase.java
./jsf-ri/systest-per-webapp/flash/web/flash7.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash8.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash2.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash5.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash4.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash3.xhtml
./jsf-ri/systest-per-webapp/flash/web/flash6.xhtml
./jsf-api/src/main/java/javax/faces/context/Flash.java

When looking through the files, I found out, that the famous Flash-Scope of Ruby on Rails (my friend Peter told me about that scope in RoR about a year ago when we where doing stuff with JSF 1.2) got ported to JSF-2.

So, what you now basically can do, is to put an object into flash-scope in one request, e.g.:

<h:form id="nextForm" prependId="false">
<c:set target="#{flash}" property="foo" value="bar" />
....
</h:form>

(Taken from ./jsf-ri/systest/web/flash01.xhtml)

and retrieve it in the next request (but not the request after that one) simply by accessing it through EL

foo = ${flash.foo}
(Taken from ./jsf-ri/systest/web/flash02.xhtml)

Also you can put objects into the flash scope in your controllers:

ELFlash.getFlash().put("key","value");

I know that looks quite dirty because one is polluting the controller with a Singleton, but when done right, you can still make your code perfectly testable 😉

The files you need to take a look at are:

  • The Interface: ./jsf-api/src/main/java/javax/faces/context/Flash.java
  • The Implementation: ./jsf-ri/src/com/sun/faces/context/flash/ELFlash.java
  • The Test-Case: ./jsf-ri/systest-per-webapp/flash/src/java/com/sun/faces/systest/FlashTestCase.java(Although the test code use some cleanup!)

Update: I found a blog post from Ed Burns about using the Flash Scope, although its still JSP based, it should also give a good introduction!

Comment Form

top