2017-10-14 78 views
2

我有一個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> 

要加載i的控制器所使用的下面方法形式:

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

問題是,成功消息總是存在(當頁面加載時這是我第一次提交表格之前)。我該如何解決它?

回答

1

您可以更改代碼,一點點:

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

但底線是更換而不是的addAttribute addFlashAttribute和@移除訊息GetMapping。