spring boot设置全局变量到前端Thymeleaf模板上

需求分析

网站使用 Spring Boot + Thymeleaf 开发,页面有很多个 Thymeleaf 视图(html页面),网站配置参数是保存在mysql数据库里的,现在想要实现传递网站配置参数至整个前台,让每个Thymeleaf 视图都能接收到网站配置参数;网站配置参数:比如网站名称、关键词、网站描述、网站底部信息等等。

实现方法:

1、找到spring boot项目的入口启动文件(main(String[] args)里有SpringApplication.run方法的)

2、 在入口启动文件里,增加一个configureThymeleafStaticVars,整个入口启动 文件关键代码如下:

    //自动装配(通过名称装配,这里不能用@Autowired)
    @Resource
    private ConfigService configService;

    /**
     * 程序入口
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(CodepayApplication.class, args);
    }
    /**
     *  加载全局变量到前端Thymelea模板上
     */
    @Resource
    private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
        //存放配置的字典集合
        Map<String,String> config = new HashMap<>();
        try {
            List<Config> configList = configService.select();
            if(configList!=null && configList.size()>0){
                for (Config c : configList){
                    config.put(c.getKey(),c.getVal());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        viewResolver.addStaticVariable("config", config);
    }
复制代码

其中viewResolver.addStaticVariable(“config”, config)就是设置你想传递到前台的数据

3、前台 Thymeleaf模板文件

<!DOCTYPE html>
<!--引入thymeleaf-->
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<p>读取配置信息</p>
网站名称:<span th:text="${config['name']}"></span>
</body>
</html>
复制代码

效果如下图:

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享