天天看點

關于springboot+thymeleaf不能引用外部靜态資源

關于springboot+thymeleaf不能引用外部靜态資源

第一次寫部落格,為了記錄一下踩的坑,大家能夠避過。花了4個小時一直在找,為什麼一直無法成功引用外部靜态資源

問題:springboot+thymeleaf 引入css、js 無效。

目錄結構如下圖

關于springboot+thymeleaf不能引用外部靜态資源
關于springboot+thymeleaf不能引用外部靜态資源
關于springboot+thymeleaf不能引用外部靜态資源

項目為springboot2.0X以上的版本,這些都引入了,應該是可以的,百度了一圈,全部都類似,改配置檔案都試過了

spring.mvc.static-path-pattern=/**
spring.mvc.static-path-pattern=/static/**           

還是不行。

-----------------------------手動分割線------------------------------------------

解決辦法:

如果你以上配置都做了,應該就可以了。

注意的要點是:引入這兩個就行了

<html lang="en" xmlns:th="http://www.thymeleaf.org">  //導入頭檔案           
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>           

springboot底層會自動配置加載目錄分别是:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

而這兩句代碼是指springboot 改變了mvc的配置

spring.mvc.static-path-pattern=/**

spring.mvc.static-path-pattern=/static/**

有同學問我th:src="@{XXXXXX}" 的作用是什麼,與src=“XXXXX”的差別是什麼

使用@關鍵字 引用位址 ,既可以是絕對路徑,也可以是相對路徑,src同理

差別在于,項目跑起來部署後,通路的資源路徑會發生改變,導緻靜态的src無法擷取資源檔案,而th:src=“@{}” 可以擷取

舉例: 在application.properties 中添加這句代碼

server.servlet.context-path=/crud           

通路的路徑也會随之改變

關于springboot+thymeleaf不能引用外部靜态資源

劃重點,如果你到了這一步還不行

那麼看看你有沒有編寫了mvc的配置類?如果是的話那就繼承WebMvcConfigurerAdapter,不要繼承WebMvcConfigurerationSupport,繼承後者表明完全接管springMvc,會導緻springBoot的預設設定都丢棄掉。

猛然落淚,留下了不學無術的眼淚,因為自己多寫了mvc配置類,結果導緻我尋找了這麼久,在此記錄一下。

一般mvc的配置類可以寫注釋@RequestMapping

未經過作者允許,不得轉載。