How to set a Flash Message in Spring Boot with Thymeleaf

Yazid Erman picture Yazid Erman · May 3, 2017 · Viewed 12.4k times · Source

I am trying to implement Flash-Messages in my project built on Spring-Boot with Thymeleaf. But I found that it's not a built in feature so far. If this is the case, what are the options to show messages to the user after redirection.

I am trying to implement the solution proposed in the link but it's not intended to work on Spring-Boot as explained in the introduction.

Answer

joshua picture joshua · Jun 11, 2017

As explained here, Inject RedirectAttributes object into your controller, then call setFlashAttribute on the object. e.g.

@GetMapping("/test1")
public String test1(RedirectAttributes redirAttrs){
    redirAttrs.addFlashAttribute("message", "This is message from flash");
    return "redirect:/test2";
}

@GetMapping("/test2")
public String test2(Model model){
    return "test2";
}

The message is now available in the model of "/test2" so in test.html, display the message e.g

<h2 th:text="${message}"></h2>