thymeleaf模板及静态资源放到系统目录下(服务器指定目录下),而非classpath下(即实现后台代码和静态资源分离)

本文介绍如何在项目中实现Thymeleaf模板及其静态资源的分离部署与热加载,通过修改配置使模板文件独立于项目代码,同时监控文件变动以实时更新模板,提升开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 场景:项目中使用到thymeleaf模板技术,模板文件在项目resources>templates目录下,模板相应的静态资源也在后台代码中,静态资源由前台同事维护,每次发布时,前台将文件给后台,后台覆盖后再由后台统一发布,比较麻烦。

  • 需求:模板文件分离及热加载,即将模板文件及其静态资源单独部署到服务器指定目录并实现热加载。

  • 分离部署:

    • 修改配置:

      • 常规的配置:

        ## 前缀prefix
        spring.thymeleaf.prefix=classpath:templates/
        ## 后缀suffix
        spring.thymeleaf.suffix=.html
        ## 类型mode
        spring.thymeleaf.mode=HTML5
        

        配置thymeleaf模板的路径为classpath下的templates目录;

      • 分离配置:

        ## 前缀prefix
        spring.thymeleaf.prefix=file:D:/template/
        ## 后缀suffix
        spring.thymeleaf.suffix=.html
        ## 类型mode
        spring.thymeleaf.mode=HTML5
        

        配置thymeleaf模板的路径为文件路径d盘下的template目录。

    • 静态资源路径:

      • 注意:模板html需要的静态资源存放路径及访问路径也要在配置文件中指定,如:

        #静态资源访问
        spring.mvc.static-path-pattern=/zm/my/**
        #静态资源存在路径
        spring.resources.static-locations=file:D:/template/
        
      
        如上,静态资源a.css存放在D:/template/路径下;
      
        ​			a.css访问路径为:http://localhost:8080/zm/my/a.css
    
    
  • 热部署:

    • 第一种,禁止缓存:

      在配置文件中配置:

      spring.thymeleaf.cache=false
      

      ​ 弊端:禁止模板缓存后,模板不缓存,每次都是重新渲染,效率方面有影响,失去了使用模板的本意(个人理解,未实际验证)。

    • 第二种:监控模板及静态资源,监控到文件发生变化后,再清除对应缓存:

      代码实现:

      • 监控文件(使用Apacha commons-io的monitor实现):

        1.引入 commons-io依赖:

        <dependency>
        		<groupId>commons-io</groupId>
        		<artifactId>commons-io</artifactId>
        		<version>2.6</version>
        </dependency>
        

        2.编写继承FileAlterationListenerAdaptor的类FileListener:

        /**
         * 监控文件变化
         */
        public class FileListener extends FileAlterationListenerAdaptor {
        
            private static Logger log = LoggerFactory.getLogger(FileListener.class);
        
            private SpringTemplateEngine springTemplateEngine;
        
            public FileListener(SpringTemplateEngine springTemplateEngine) {
                this.springTemplateEngine = springTemplateEngine;
            }
        
            /**
             * 文件创建执行
             */
            public void onFileCreate(File file) {
        
            }
        
            /**
             * 文件创建修改,监控到文件有修改后清除缓存
             */
            public void onFileChange(File file) {
                log.info(file.getName() + " has changed...");
                springTemplateEngine.clearTemplateCacheFor(file.getName().substring(0, file.getName().indexOf(".")));
        
            }
        
            /**
             * 文件删除
             */
            public void onFileDelete(File file) {
        
            }
        
            /**
             * 目录创建
             */
            public void onDirectoryCreate(File directory) {
            }
        
            /**
             * 目录修改
             */
            public void onDirectoryChange(File directory) {
        
            }
        
            /**
             * 目录删除
             */
            public void onDirectoryDelete(File directory) {
        
            }
        
        }
        

        3.开启监控:

        @Controller
        @RequestMapping("is/api/v1")
        public class  MyController extends BaseController {
        
            @Autowired
            SpringTemplateEngine springTemplateEngine;
        
             @PostConstruct
             private void init() throws Exception {
                 listen();
             }
        
            private void listen() throws Exception {
            log.info("FileListener begin...");
            // 监控目录
            String rootDir = "/data/server/templates/";
            // 轮询间隔  秒
            long interval = TimeUnit.SECONDS.toMillis(1);
            // 创建过滤器
            IOFileFilter directories = FileFilterUtils.and(
            FileFilterUtils.directoryFileFilter(),
            HiddenFileFilter.VISIBLE);
            IOFileFilter files = FileFilterUtils.and(
            FileFilterUtils.fileFileFilter());
            IOFileFilter filter = FileFilterUtils.or(directories, files);
            // 使用过滤器
            FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);
        
            observer.addListener(new FileListener(springTemplateEngine));
            //创建文件变化监听器
            FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
            // 开始监控
            monitor.start();
            }
        }
        
        
        
      • 监控到文件发生变化时,清除模板缓存:

        如上边代码:

        /**
        * 文件创建修改,监控到文件有修改后清除缓存
        */
        public void onFileChange(File file) {
            log.info(file.getName() + " has changed...");
                springTemplateEngine.clearTemplateCacheFor(file.getName().substring(0, file.getName().indexOf(".")));
        
        }
        

        使用springTemplateEngine.clearTemplateCacheFor(fileName)清除缓存。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值