More than 10 years of experience in Enterprise Applications development, and Project Management (since June 2001). Specialties: Enterprise Applications, J2EE, J2SE, Spring Framework, Spring Security, Spring Webflow, JPA and JDBC, JMX, JAXB, JUnit; XML, XSLT and XSL-FO; HTML/CSS, Javascript, JSON, jQuery/jQuery UI; RDBMS (Oracle, SQL Server, MySQL), PL/SQL; UML; Mobile Applications, mostly in Objective-C targeted iPhone/iPad Michal is a DZone MVB and is not an employee of DZone and has posted 12 posts at DZone. You can read more from them at their website. View Full User Profile

Spring MVC - Flash Attributes

  • submit to reddit
The latest incarnation of the Spring Framework (3.1) brought an interesting feature called Flash Attributes. It is a remedy for the problem mentioned a long time ago, in one of my posts: Spring MVC - Session Attributes handling. This problem can be described in few words: if we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's @SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient.

Below you will find an example of Flash Attributes usage, before you start reviewing it, read Using flash attributes section of Spring documentation.

Suppose that we have two controllers: AController and BController, first one will prepare some data and pass to the second using Flash Attributes after the form submission. On the AController we will have something like this:
@RequestMapping(method = RequestMethod.POST)
public String handleFormSubmission(..., final RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttribute("AttributeName", value);
    return "redirect:to_some_url_handled_by_BController";
When the form will be submitted, attribute value will be stored as Flash Attribute named "AttributeName", and thanks to the Spring, will be passed to BController, where it can be used for example in following way:
public class SearchCriteriaHandler {
    @RequestMapping(method = RequestMethod.GET)
    public void handleGetRequest(@ModelAttribute("AttributeName") final SomeType value) {

Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes - at this point value passed from AController will become a model attribute for the BController. Note, that because we also defined this attribute as the Session Attribute, it will be automatically stored for future usage within this controller, after the GET request handling.

Let me say that I was waiting for this feature for the long time, ;)
Published at DZone with permission of Michal Jastak, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)