How to set a Flash Message in Spring Boot with Thymeleaf

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.

Do NOT follow this link or you will be banned from the site!