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的模板中添加一個版本號,來實現緩存的更新。
步驟
- 在CSS文件的URL后面添加一個查詢參數,如:
- 在應用的啟動類中,配置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
- 解決方法