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:
@Controller
...
@SessionAttributes("AttributeName")
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, ;)
Related Posts: Spring MVC - Session Attributes handling
Any reason here to declare RedirectAttributes as final. Would like to know.
ReplyDeleteThanks for such a simple article.
same question
ReplyDelete@catchmahesh, @id - at least one :), but pretty important - re-assigning method parameters is bad practice. When you mark method parameters as final, you clearly express the intention, and avoid accidental reassignment :)
ReplyDeleteThank you Michal - Found it useful today.
ReplyDeleteThis is still relevant in 2015. I just got caught out by this on a redirect and found the solution here. Thank you.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteStill found this useful today in 2016! Thanks!
ReplyDeleteStill useful in 2017 :)
ReplyDeleteStill useful in 2018 xD
ReplyDelete