Spring Boot Thymeleaf第一次进页面不加载CSS如何解决

知识库

Spring Boot Thymeleaf第一次进页面不加载CSS如何解决

2023-10-28 17:44


本文将介绍解决Spring Boot Thymeleaf第一次进页面不加载CSS的方法。

                                            
    
    

当使用Spring Boot结合Thymeleaf开发Web应用时,有时会遇到第一次访问页面时CSS样式无法正确加载的问题。

解决方法

这个问题通常是由于Thymeleaf的缓存机制导致的。Thymeleaf会将编译过的HTML缓存起来,以提高性能。但是,当引入CSS文件时,由于缓存机制,第一次访问页面时可能无法加载最新的CSS文件。

为了解决这个问题,可以在Thymeleaf的模板中添加一个版本号,来实现缓存的更新。

步骤

  1. 在CSS文件的URL后面添加一个查询参数,如:
  2. 在应用的启动类中,配置Thymeleaf的缓存模式为不使用缓存,代码如下:
        
@Configuration
public class ThymeleafConfig implements WebMvcConfigurer {    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }    @Bean
    public TemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.addDialect(new LayoutDialect());
        engine.setCacheManager(nonCacheManager());
        return engine;
    }    @Bean
    public ICacheManager nonCacheManager() {
        return new NonCacheManager();
    }
}
        
    

通过以上步骤,每次更新CSS文件时只需要修改查询参数的版本号,Thymeleaf会认为有新的资源文件,从而重新加载CSS文件。

总结

通过在Thymeleaf模板中添加版本号,并禁用Thymeleaf的缓存机制,可以解决Spring Boot Thymeleaf第一次进页面不加载CSS的问题。

希望本文能对你解决这个问题有所帮助!


標簽:
  • Spring Boot
  • Thymeleaf
  • CSS
  • 解决方法