Search code examples
springspring-mvcsweetalert2

Show error or success from controller


I am using sweetAlert to show popUp message and i want to know if there's any why to show this alert from the controller

myPage.html

<form th:object="${ecran}"  th:action="@{/createIssue}"  method="post"  >
 ...

<a class="btn btn-outline-danger" type="submit" >Valider la demande</a>
</form>

My Alert

swal("Are you sure you want to do this?", {
buttons: ["Oh noez!", true],
});

myController.java

@PostMapping("/createIssue")
public String creerUneDemande(@Valid @ModelAttribute("ecran") Ecran ecran, BindingResult result,
        RedirectAttributes redirectAttributes) {
...

}

Solution

  • You can achieve the same by setting a flag in controller using modal attribute and based on the flag value you can show the alert in view page.

    @PostMapping("/createIssue")
    public String creerUneDemande(@Valid @ModelAttribute("ecran") Ecran ecran, BindingResult result,
            RedirectAttributes redirectAttributes) {
    
    ...
    //if everything working fine then set the flag value
    redirectAttributes.addFlashAttribute("flag","showAlert");
    }
    

    In the view page accept the value of the flag inside javascript code and execute the condition something like below.

    if('${flag}' == 'showAlert'){
     swal("Are you sure you want to do this?", {
     buttons: ["Oh noez!", true],
     });
    }