我有spring-boot
个应用,Thymeleaf
。我有一个非常基本的场景。有一个表单,当用户点击提交按钮时,表单数据应该发送到控制器,但是同一页面中的应该显示成功消息。
表单非常简单:
<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>
要加载表单,我在控制器中使用了以下方法:
@GetMapping("/suggest-event")
public String suggestEvent(@RequestParam(value = "message", required = false) String message) {
model.addAttribute("message",message);
return "/suggested-event/suggestEvent";
}
然后回答帖子请求的方法:
@PostMapping("/suggest-event")
public String receiveSuggestedEvent( RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggest-event";
}
问题是,成功消息总是存在(当页面第一次加载时,在我提交表单之前)。我该如何解决?
答案 0 :(得分:6)
您可以稍微更改一下代码:
site-packages
我在html中显示消息的解决方案:
@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";
}
但是底线是替换addFlashAttribute而不是addAttribute并从@GetMapping中删除消息。