首页 > 解决方案 > Spring thymeleaf:如何显示警报

问题描述

我正在为一个项目开发一个crud。我想在管理员编辑员工、产品(无论是什么)时显示警报,以显示带有“已成功编辑”消息的警报。我可以显示此消息,但我想在警报中显示它。

我的模型:

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

}

标签: springspring-bootthymeleaf

解决方案


您可以使用 Jquery 的document ready功能在每次用户重定向到您的成功页面时显示警报。所以每次页面加载时,浏览器都会自动运行文档就绪功能(更多关于jquery文档就绪功能请参考官方文章-https:
//learn.jquery.com/using-jquery-core/document-ready/

此外,如果您想根据某些动态条件显示警报消息,您也可以使用thymeleaf + javascript 。有关如何在 javascript 中使用 thymeleaf 的更多详细信息,请参阅此官方文档 -
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining


推荐阅读