Spring Boot 如何在Sping Boot with Thymeleaf中设置Flash消息

rbl8hiat  于 2022-12-04  发布在  Spring
关注(0)|答案(2)|浏览(184)

我正在尝试在我的项目中实现Flash消息,这个项目是在Spring-Boot上用Thymeleaf构建的。但是我发现到目前为止,它还不是一个内置的特性。如果是这样的话,在重定向之后,有什么选项可以向用户显示消息呢?
我正在尝试实现link中提出的解决方案,但它并不打算在介绍中解释的Spring-Boot上工作。

fhg3lkii

fhg3lkii1#

here所述,将RedirectAttributes对象注入控制器,然后在该对象上调用setMeOH Attribute。例如:

@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";
}

消息现在在“/test 2”模型中可用,因此在test.html中显示消息,例如

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

nbysray52#

您可以添加此代码,它将如下所示

<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>

相关问题