In a normal Spring MVC application, every form submitted POSTs the form data to the server; a normal Spring Controller retrieves the data from those forms from the request and processes it further. Once the operation is successful, the user is forwarded to another page showing a message that the operation was a success.
Traditionally, if we handle this scenario via the POST/Forward/GET
pattern, then it may sometimes cause multiple form submission issues. The user might press F5 and the same form will be submitted again. To resolve this issue, the POST/Redirect/GET
pattern is used in many web applications. Once the user's form is submitted successfully, we redirect the request to another success page instead of forwarding it. This makes the browser perform a new GET request and load the GET page. Thus if the user even presses F5 multiple times, the GET request gets loaded instead of submitting the form again and again.
While the POST/Redirect/GET
pattern seems to perfectly solve the problem of multiple form submissions, it adds one more problem of retrieving request parameters and attributes from the initial POST request. Usually, when we perform an HTTP request redirection, the data stored in the original request is lost, making it impossible for the next GET request to access it after redirection. Flash attributes can help in such cases. Flash attributes provide a way for us to store information that is intended to be used in another request. Flash attributes are saved temporarily in a session to be available for an immediate request after redirection.
In order to use Flash attributes in your Spring MVC application, just add the RedirectAttributes redirectAttributes
parameter to your Spring Controller's method as follows:
@RequestMapping public String welcome(Model model, RedirectAttributes redirectAttributes) { model.addAttribute("greeting", "Welcome to Web Store!"); model.addAttribute("tagline", "The one and only amazing web store"); redirectAttributes.addFlashAttribute("greeting", "Welcome to Web Store!"); redirectAttributes.addFlashAttribute("tagline", "The one and only amazing web store"); return "redirect:/welcome/greeting"; }
In this example, we stored two attributes, namely greeting
and tagline
, in Flash attributes; thus when the redirection happens to the /welcome/greeting
(the greeting
controller method in HomeController
) request mapping method, it will have access to those variable values that are already in the model object.