How to set a Flash Message in Spring Boot with Thymeleaf
Asked Answered
F

2

15

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.

Fleece answered 3/5, 2017 at 5:39 Comment(1)
Yes it is supported out-of-the-box... Please see docs.spring.io/spring/docs/current/spring-framework-reference/… which explains that.Stopcock
C
24

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>
Charleen answered 11/6, 2017 at 20:58 Comment(0)
S
0

You could add this code and it will look like this

<div class="alert alert-success" role="alert"
                             th:if="${message}">
                            <span th:text="${message}"></span>
                            <button aria-label="Close" class="btn-close" data-bs-dismiss="alert"
                                    type="button"></button>
                        </div>
Subplot answered 1/12, 2022 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.