springboot+thymeleaf后端设置全局变量前端js接收

  1. 目的:前端所有地方都可以拿到统一定义的变量,可以定义的java代码中,application.yam文件或者配置文件中

  2. 第一步:在spring能够管理bean的地方添加如下代码,我这里在main启动入口下面直接添加了

    package com.ruoyi;
    
    import com.google.common.collect.Maps;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.core.env.Environment;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.thymeleaf.spring5.view.ThymeleafViewResolver;
    
    import javax.annotation.Resource;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 启动程序
     *
     * @author ruoyi
     */
    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
    @MapperScan("com.ruoyi.*.mapper")
    public class RuoYiApplication {
        public static void main(String[] args) {
            // System.setProperty("spring.devtools.restart.enabled", "false");
            SpringApplication.run(RuoYiApplication.class, args);
            System.out.println("(♥◠‿◠)ノ゙  DIX启动成功   ლ(´ڡ`ლ)゙  \n" +
                    " .-------.       ____     __        \n" +
                    " |  _ _   \\      \\   \\   /  /    \n" +
                    " | ( ' )  |       \\  _. /  '       \n" +
                    " |(_ o _) /        _( )_ .'         \n" +
                    " | (_,_).' __  ___(_ o _)'          \n" +
                    " |  |\\ \\  |  ||   |(_,_)'         \n" +
                    " |  | \\ `'   /|   `-'  /           \n" +
                    " |  |  \\    /  \\      /           \n" +
                    " ''-'   `'-'    `-..-'              ");
        }
    
    
        @Resource
        private Environment env;
    
        @Resource
        private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
            if(viewResolver != null) {
                Map<String, Object> vars = Maps.newHashMap();
                vars.put("ctx", env.getProperty("ctx"));
                viewResolver.setStaticVariables(vars);
            }
        }
    
    }
    
    
    
  3. 然后到前端的代码,把这段代码放到header.html,统一加载就行了

    <script th:inline="javascript">
        const ctx = '[(${ctx})]';
        console.log(ctx)
    </script>
    
  4. 我的 application.yml文件配置,添加一行变量就可以了

    #js ajax请求统一添加路径
    ctx: http://127.0.0.1:8085/
    
Logo

快速构建 Web 应用程序

更多推荐