Implementing Flash Scope in Java Web Applications
While working recently on a Spring MVC project I found myself wishing it supported flash scope. I hunted around for a simple solution but couldn’t find anything that didn’t rely on having to import large framework libraries. After a little thought I came up with the following simple and lightweight solution that has worked really well for me. I’ve included the code for this below so feel free to try it out.
What is Flash Scope
Flash scope is a useful part of many web frameworks. It allows the use of the post/redirect/get design pattern to alleviate many of the problems associated with handling multiple submits or resubmission of data in browser requests to the server.
Flash scope is an additional scope to those provided in a standard Java Web application (page, request, session and application). Any attributes held in flash scope will be available for the duration of the current request, and the subsequent request too.
To implement flash scope in my application, I added a servlet filter that checks for request attribute names starting with ‘flash.‘. When it finds such an attribute, it ensures that it is made available in the subsequent request by temporarily storing it in the user’s session, and then reinstating it when the next request is received.
For example, to add a message to flash scope, just use the regular syntax for adding a request scoped attribute and let the fiter take care of it:
The above attribute can then be accessed in the redirect target JSP using EL or scriptlet syntax (omitting the ‘flash.‘ prefix):
Here’s the code for the filter:
You can see from the listing, that the filter stores the flash scoped parameters in a session scoped map called FLASH_SESSION_KEY. Before the request is processed by the filter chain, the flash attributes are retrieved from the session and added to request scope; after the chain has finished, any new flash scoped parameters are stored in a new session scoped map.
Note that the attributes have the ‘flash.‘ prefix removed when added to the session scoped map – this not only ensures that they can be accessed using their ’short name’, but that they are only kept in the session for one extra request.
This approach is not Spring specific and should work with and Java Web framework. I’ve omitted the configuration for the filter as there are loads of examples of how to do this on the Internet already.