forms - Thymeleaf:点击提交按钮后显示成功消息

标签 forms spring-boot thymeleaf

我有一个 spring-boot应用程序,与 Thymeleaf .我有非常基本的场景。有一个表单,当用户点击提交按钮时,表单数据应该发送到 Controller ,但是在同一页面中,应该会显示成功消息。

表格非常简单:

<form th:action="@{/suggest-event}"  method="post">
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
<div th:switch="${message}">
    <div th:case="'Success'" class="alert alert-success">
        <strong>Success!</strong> Operation performed successfully.
    </div>
    <div th:case="'Failed'" class="alert alert-danger">
        <strong>Failure!</strong> Operation failed. Please try again 
    </div>
</div>

要加载表单,我在 Controller 中使用了以下方法:

@GetMapping("/suggest-event")
public String suggestEvent(@RequestParam(value = "message", required = false) String message) {

    model.addAttribute("message",message);
    return "/suggested-event/suggestEvent";
}

然后是回答post请求的方法:

@PostMapping("/suggest-event")
public String receiveSuggestedEvent( RedirectAttributes redirectAttributes) {

    redirectAttributes.addAttribute("message", "Success");
    return "redirect:/suggest-event";
}

问题是,成功消息始终存在(第一次加载页面时,以及在我提交表单之前)。我该如何解决?

最佳答案

您可以稍微更改代码:

@GetMapping("/suggest-event")
public String suggestEvent() {
    return "/suggested-event/suggestEvent";
} 

@PostMapping("/suggest-event")
public String receiveSuggestedEvent(BindingResult result, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("message", "Failed");
    redirectAttributes.addFlashAttribute("alertClass", "alert-danger");
    if (result.hasErrors()) {
        return "redirect:/suggest-event";
    }
    redirectAttributes.addFlashAttribute("message", "Success");
    redirectAttributes.addFlashAttribute("alertClass", "alert-success");
    return "redirect:/suggest-event";
}

我在 html 中显示消息的解决方案:
<div th:if="${message}" th:text="${message}" th:class="${'alert ' + alertClass}"/>

但底线是替换 addFlashAttribute 而不是 addAttribute 并从@GetMapping 中删除消息。

关于forms - Thymeleaf:点击提交按钮后显示成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46744586/

相关文章:

java - Spring MVC + Thymeleaf 将单个对象发送到 Controller

forms - 无法确定属性 "id"的访问类型 - HandleRequest 失败,除非我公开实体 ID

javascript - 如何删除javascript中的表单自动填充

java - application.yml 中的@Value 返回错误值

spring-mvc - 在 Spring Boot 应用程序中使用 JSP 和 Thymeleaf View

java - thymeleaf 是一种什么样的解决方案?

java - 如何通过关键变量 thymeleaf 从模型获取模型图

forms - 在表单中渲染自定义实体类型字段(Symfony)

python - Django 表单字段验证

java - 如何使用 spring-boot-starter-data 将 cassandra 与 postgres 一起使用