溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot+thymeleaf靜態(tài)資源引入的方法

發(fā)布時(shí)間:2022-03-03 15:39:56 來源:億速云 閱讀:438 作者:iii 欄目:web開發(fā)

本文小編為大家詳細(xì)介紹“SpringBoot+thymeleaf靜態(tài)資源引入的方法”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“SpringBoot+thymeleaf靜態(tài)資源引入的方法”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

  一、靜態(tài)資源的映射規(guī)則

  1.對(duì)哪些目錄映射?

  classpath:/META-INF/resources/

  classpath:/resources/

  classpath:/static/

  classpath:/public/

  /:當(dāng)前項(xiàng)目的根路徑

  意思是:我們?cè)谏厦娴奈鍌€(gè)目錄下放靜態(tài)資源文件(比如:jq.js等),可以直接訪問(類似以前web項(xiàng)目的webapp下,放到其他目錄無法被訪問。

  2.為什是這幾個(gè)目錄呢?

  2.1看源碼就知道

  SpringBoot自動(dòng)配置的WebMvcAutoConfirarution.java類:

  @Override

  public void addResourceHandlers(ResourceHandlerRegistry registry) {

  if (!this.resourceProperties.isAddMappings()) {

  logger.debug("Default resource handling disabled");

  return;

  }

  Duration cachePeriod=this.resourceProperties.getCache().getPeriod();

  CacheControl cacheControl=this.resourceProperties.getCache()

  .getCachecontrol().toHttpCacheControl();

  if (!registry.hasMappingForPattern("/webjars/**")) {

  customizeResourceHandlerRegistration(registry

  .addResourceHandler("/webjars/**")

  .addResourceLocations("classpath:/META-INF/resources/webjars/")

  .setCachePeriod(getSeconds(cachePeriod))

  .setCacheControl(cacheControl));

  }

  String staticPathPattern=this.mvcProperties.getStaticPathPattern();

  if (!registry.hasMappingForPattern(staticPathPattern)) {

  customizeResourceHandlerRegistration(

  registry.addResourceHandler(staticPathPattern)

  .addResourceLocations(getResourceLocations(

  this.resourceProperties.getStaticLocations()))

  .setCachePeriod(getSeconds(cachePeriod))

  .setCacheControl(cacheControl));

  }

  }

  ResourceProperties

  @ConfigurationProperties(prefix="spring.resources", ignoreUnknownFields=false)

  public class ResourceProperties {

  //我們可以看到靜態(tài)資源的映射路徑

  private static final String[] CLASSPATH_RESOURCE_LOCATIONS={

  "classpath:/META-INF/resources/", "classpath:/resources/",

  "classpath:/static/", "classpath:/public/" };

  ...

  }

  總的來說:

  WebMvcAutoConfiguration類自動(dòng)為我們注冊(cè)了如下目錄為靜態(tài)資源目錄,也就是說直接可訪問到資源的目錄。

  classpath:/META-INF/resources/

  classpath:/resources/

  classpath:/static/

  classpath:/public/

  /:當(dāng)前項(xiàng)目的根路徑

  優(yōu)先級(jí)從上到下。

  所以,如果static里面有個(gè)index.html,public下面也有個(gè)index.html,則優(yōu)先會(huì)加載static下面的index.html,因?yàn)閮?yōu)先級(jí)!

讀到這里,這篇“SpringBoot+thymeleaf靜態(tài)資源引入的方法”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI