如何使用 Thymeleaf 在 Spring Boot 中设置 Flash 消息 [英] How to set a Flash Message in Spring Boot with Thymeleaf
问题描述
我正在尝试在我的基于 Spring-Boot 和 Thymeleaf 的项目中实现 Flash-Messages.但我发现到目前为止它不是内置功能.如果是这种情况,重定向后向用户显示消息的选项是什么.
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.
我正在尝试实施 link 中提出的解决方案,但它并不适用在介绍中解释的 Spring-Boot 上.
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.
推荐答案
如上解释 此处,将 RedirectAttributes 对象注入您的控制器,然后在该对象上调用 setFlashAttribute.例如
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";
}
该消息现在可以在/test2"模型中使用,因此在 test.html 中,显示该消息,例如
The message is now available in the model of "/test2" so in test.html, display the message e.g
<h2 th:text="${message}"></h2>
这篇关于如何使用 Thymeleaf 在 Spring Boot 中设置 Flash 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!