Spring MVC Flash Attributes Example

A very common scenario in a MVC application is to Submit a form and show a success page along with some information about the submitted data. Now when we submit the form and show the success page, we lose the request params that were available during submitting the form. So we are not able to show those on the new page that we redirected to.

Spring MVC Flash Attributes provide a way to store those attributes that are required to be shown on the next page at a redirect on a Post/Redirect/Get.

Spring MVC uses FlashMapand FlashMapManager to support Flash Attributes.
FlashMapis used to hold flash attributes while FlashMapManageris used to store, retrieve, and manage FlashMap instances.
Each request in Spring MVC has a input FlashMap that stores the previous request attributes and a output FlashMap that carries the current request attributes to next request.

If you are working with annotated controller, then you need not worry about flash map.An argument with type RedirectAttributes is used to handle the Flash Attributes. Flash attributes added via RedirectAttributes are automatically propagated to the output FlashMap. Similarly, after the redirect, attributes from the input FlashMap are automatically added to the Model of the controller serving the target URL

Example: Spring MVC Flash Attributes Using RedirectAttributes

1. Spring Dispactcher Servlet

2. Create a Employee Object

3. Create a form to get the employee details

4. Create a Controller

In the Controller we will first create a ModelAndView to show the Employee Form. We use a command-employee here.
Once the form is submitted we go to the addEmployee() method. Here we get the details filled on the form. In this method we use the RedirectAttributes to store the flash attributes. Once we store the attributes we will show the welcome page. In the showEmployee() method we get the flash attributes using the @ModelAttribute

5. Create a welcome page to show the Flash Attributes

On the welcome page we will show the firstName and lastName that we stored as flash attributes.

6. Output

Features of Spring MVC | Spring MVC Flash Attributes Example - KSCodes
Spring MVC Tutorials with Examples | Spring MVC Flash Attributes Example - KSCodes

Download Full Code – SpringMVCFlashAttributes.zip