SpringBoot2 X 靜態檔案配置

2021-10-02 15:02:51 字數 1887 閱讀 6181

spring boot 缺省會挨個從

meta/resources > resources > static > public 裡面找是否存在相應的資源,如果有則直接返回。

預設配置:

spring.resources.static-locations = classpath:/meta-inf/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
建議將靜態資源和**分離,將靜態資源檔案儲存在cdn

spring.resources.static-locations=classpath:/templates/,classpath:/static/,classpath:/public/
addresourcehandler方法是設定訪問路徑字首,addresourcelocations方法設定資源路徑,如果你想指定外部的目錄也很簡單,直接addresourcelocations指定即可,**如下:

registry.addresourcehandler("/**")

.addresourcelocations("classpath:/templates/")

.addresourcelocations("classpath:/static/")

.addresourcelocations("classpath:/public/")

.addresourcelocations("file:" + outside_static);

@configuration

public class staticfilepathconfig implements webmvcconfigurer ")

// private string staticaccesspath;

// @value("$")

// private string uploadfolder;

@override

public void addresourcehandlers(resourcehandlerregistry registry) catch (filenotfoundexception e)

string outside_templates=path.getparentfile().getparentfile().getparent()+file.separator;

outside_templates=outside_templates.substring(5,outside_templates.length());

//string outside_static=path.getparentfile().getparentfile().getparent()+file.separator+"outsidefile"+file.separator+"jacococoverage"+file.separator;

system.out.println(outside_static);

//file:/data/github/testmanagement/target/

registry.addresourcehandler("/**")

.addresourcelocations("classpath:/templates/")

.addresourcelocations("classpath:/static/")

.addresourcelocations("classpath:/public/")

.addresourcelocations("file:" + outside_static);

// super.addresourcehandlers(registry);

}}

spring boot2 x訪問靜態資源

此處對比兩個spring boot版本訪問靜態資源的區別 jdk分別為1.7與1.8 1.5.9.release 2.1.6.release 資源未被攔截 可以訪問 可以訪問 資源被攔截 可以訪問 不可以訪問 由此可見,如果spring boot版本為2.x,那存在配置了靜態資源後不能被訪問的情況。...

SpringBoot 2 X 訪問靜態資源

我專案中的檔案如下,使用的是spring boot 2.2.6 也就是2.x版本 html檔案 資源目錄 controller層 訪問html的時候,發現靜態資源沒有訪問到,在html檔案中,靜態資源路徑寫的是沒問題的,在springboot1.x的時候也是沒問題的,但是為什麼訪問不到?究其原因是使...

springBoot2 x靜態資源配置和啟動熱載入

新增靜態資源檔案,外部可以直接訪問位址 import org.springframework.stereotype.component import org.springframework.web.servlet.config.annotation.resourcehandlerregistry i...