如何使用Spring Boot Thymeleaf设置Flash 消息

Flash 消息(一次性通知)通常用于向用户显示操作的结果:

Spring Boot 在 RedirectAttributes 界面中提供了这个确切的功能。它使用FlashMap数据结构将闪存消息存储为键值对。Thymeleaf 自动支持读取模板文件中的这些属性,就像它处理普通模型属性一样。

闪存消息的一个方便功能是它们在重定向后幸存下来(与普通模型属性相反)。请看以下示例:

@PostMapping("/somePostAction")
public String somePostAction(Model model, RedirectAttributes redirAttrs) {
    if (!everythingOkay()) {
        redirAttrs.addFlashAttribute("error", "The error XYZ occurred.");
        return "redirect:/settings/";
    }

    myService.doSomething();
    redirAttrs.addFlashAttribute("success", "Everything went just fine.");
    return "redirect:/settings/";
}

@GetMapping("/")
public String index(Model model) {

    return "settings/index";
}

somePostAction端点设置success(通知用户一切正常)或​​​​​​​error flash 属性(发生了特定错误)。

请注意,在任一情况下,都会重定向到/settings/终结点。由于闪存消息在重定向后仍可存活,因此它们在/settings/终结点的模板中也可用。​​​​​​​

在那里,它们可以像其他属性一样使用:

<h1>Settings</h1>
<div class="alert alert-primary" role="alert" th:text="${success}" th:if="${success}"></div>
<div class="alert alert-danger" role="alert" th:text="${error}" th:if="${error}"></div>

显然,对于较大的应用程序,您需要更复杂的错误管理系统,但是对于小型原型来说,细分为“成功”和多个“错误”状态通常就足够了。

猜你喜欢

转载自blog.csdn.net/allway2/article/details/128226291
今日推荐