Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database Thymeleaf:将数据库内容添加到每个页面的页脚。最佳实践?_Database_Spring Boot_Thymeleaf - Fatal编程技术网

Database Thymeleaf:将数据库内容添加到每个页面的页脚。最佳实践?

Database Thymeleaf:将数据库内容添加到每个页面的页脚。最佳实践?,database,spring-boot,thymeleaf,Database,Spring Boot,Thymeleaf,最佳做法是什么? 我将Spring Boot与Thymeleaf一起使用,并希望在每个html页面的底部显示一个电子邮件地址作为联系信息。电子邮件地址存储在数据库中,可以在运行时更改 我所知道的: 我可以使用Thymeleaf片段创建带有硬编码电子邮件的页脚,并将此页脚包含到我的所有布局中。这当然有效,但不是动态的 我可以在控制器中执行数据库查询,并将电子邮件添加到模型中。页脚将从模型中获取显示字符串。这也可以,但需要我将数据库查询和模型添加到控制器的所有功能中。这将是一片混乱 我不知道的:

最佳做法是什么?

我将
Spring Boot
Thymeleaf
一起使用,并希望在每个html页面的底部显示一个电子邮件地址作为联系信息。电子邮件地址存储在
数据库中
,可以在运行时更改

我所知道的:

  • 我可以使用Thymeleaf片段创建带有硬编码电子邮件的页脚,并将此页脚包含到我的所有布局中。这当然有效,但不是动态的
  • 我可以在控制器中执行数据库查询,并将电子邮件添加到模型中。页脚将从模型中获取显示字符串。这也可以,但需要我将数据库查询和模型添加到控制器的所有功能中。这将是一片混乱
我不知道的:

  • 我该如何优雅地解决这个问题?通过访问SpringBean->返回DB查询,我可以从Thymeleaf实现一个数据库调用。但这似乎是不对的,是吗

    • 您可以使用所谓的@ControllerAdvice注释。它可用于为每个控制器的模型属性添加内容(取决于您如何指定它)

      定义测试控制器,它位于包“com.example.controller”中

      添加全局模型

      @ControllerAdvice("com.example.controller")
      public class testAdvice {
        @ModelAttribute("email")
        public void addGlobalEmail() {
            return "some@email.com";
        }
      }
      
      您应该能够访问每个模板上的${email}

      在ControllerAdvice中,您可以注入数据库服务并从中获取相关数据


      您可以查看此网站以获取参考

      Thx以获取您的答案,与我的第二种方法相比,这似乎是一个真正的改进。我将尝试一下,尽管我怀疑这是否是最佳实践?
      @ControllerAdvice("com.example.controller")
      public class testAdvice {
        @ModelAttribute("email")
        public void addGlobalEmail() {
            return "some@email.com";
        }
      }