Jeff
Jeff

Reputation: 8421

Thymeleaf: Show a success message after clicking on submit button

I have a spring-boot application, with Thymeleaf. I have pretty basic scenario. There is a form, and when the user clicks on the submit button, the forms data should be sent to the to the controller, but in the same page a success message should shows up.

The form is pretty simple:

<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>

To load the form I used the below method in controller:

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

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

and then the method to answer the post request:

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

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

The problem is, the success message is always there (when the page loads for the first time, and before I submit the form). How can I fix it?

Upvotes: 7

Views: 24944

Answers (1)

J.Taghipour
J.Taghipour

Reputation: 201

You can change the code a little bit:

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

My solution to show message in html :

<div th:if="${message}" th:text="${message}" th:class="${'alert ' + alertClass}"/>

But the bottom line is replacing addFlashAttribute instead of addAttribute and removing message from @GetMapping.

Upvotes: 20

Related Questions