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>

效果如下图:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值