Search code examples
springspring-bootthymeleaf

Spring thymeleaf: how to show an alert


I am developing a crud for a project. I would like to show an alert when the administrator edits an employee, product, whatever it is, to show an alert with the message "successfully edited". I can show this message, but I wanted to show it in an alert.

My model:

// Edit
@GetMapping("/dashboard/contato/editar/{id}")
public String edit(@PathVariable("id") Long id, Model model)
{   
    Contato contato = contatoService.findById(id);
    model.addAttribute("contato", contato);

    return "dashboard/pages/contato/editar";
}

@RequestMapping("/dashboard/contato/editar/{id}")
public String update(@Valid Contato contato, BindingResult result, RedirectAttributes attributes,Model model)
{
    if(result.hasErrors()) {
        attributes.addFlashAttribute("error", "Verifique se os campos 
        obrigatórios foram preenchidos!");
        return "redirect:/dashboard/contato/editar/{id}";
    }else{
        contatoService.save(contato);
        attributes.addFlashAttribute("success", "Editado com sucesso!");
        return "redirect:/dashboard/contato";
    }

}

Solution

  • You can use Jquery's document ready function to show alert each time user redirects to your success page. So when each time the page loaded, browser will automatically runs the document ready function ( For more on jquery document ready function refer to the official article -
    https://learn.jquery.com/using-jquery-core/document-ready/

    Moreover you can user thymeleaf + javascript as well if you want to show alert message based on some dynamic condition. For more details on how to use thymeleaf with javascript , refer this official documentation -
    https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining