Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Flash Message in Spring Boot with Thymeleaf

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.

like image 475
Yazid Erman Avatar asked May 03 '17 05:05

Yazid Erman


1 Answers

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>
like image 93
joshua Avatar answered Sep 20 '22 16:09

joshua