Flash messages (one-time notifications) are commonly used to display the result of an operation to your users:
Spring Boot offers this exact functionality in the RedirectAttributes
interface. It uses the FlashMap
data structure to store the flash messages as key-value pairs. Thymeleaf automatically supports reading those attributes in the template files the same way it handles ordinary model attributes.
One handy feature of flash messages is that they survive redirects (in contrast to normal model attributes). Have a look at the following example:
@PostMapping("/somePostAction") public String somePostAction(Model model, RedirectAttributes redirAttrs) { if (!everythingOkay()) { redirAttrs.addFlashAttribute("error", "The error XYZ occurred."); return "redirect:/settings/"; } myService.doSomething(); redirAttrs.addFlashAttribute("success", "Everything went just fine."); return "redirect:/settings/"; } @GetMapping("/") public String index(Model model) { return "settings/index"; }
The somePostAction
endpoint either sets the success
(informing the user, that everything went fine) or the error
flash attribute (a specific error has occurred).
Notice that a redirect to the /settings/
endpoint follows in either case. Since the flash messages survive redirects, they are available in the template of the /settings/
endpoint as well.
There, they can be used like other attributes:
<h1>Settings</h1> <div class="alert alert-primary" role="alert" th:text="${success}" th:if="${success}"></div> <div class="alert alert-danger" role="alert" th:text="${error}" th:if="${error}"></div>
Obviously you need a more sophisticated error management system for larger applications, but the subdivision into a “success” and multiple “error” states is often sufficient for small prototypes.
I just wanted to add that this uses bootstrap for styling – I don’t think it is mentioned in the article anywhere and wanted to clarify for other readers!
You can also use redirAttrs.addAttribute(String, string) if you want!
Thank you, this is a really handy interface to obtain weather data with python.
I felt a bit homeless after my usual weather provider stopped their service, but now I can blow new life into my old weather display.