SpringBoot配置静态资源映射

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SpringBoot配置静态资源映射
SpringBoot 配置静态资源映射
(嵌⼊式servlet容器)先决知识
1. request.getSession().getServletContext().getRealPath("/"),这个很重要,将其称为 docBase,即 “⽂档基⽬录”
2. 在单模块项⽬中,如果不存在 src/main/webapp ⽬录,则 docBase 被设置为C盘下临时的随机⽬录,例如
C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.2872246570823772896.8080\
3. 在多模块项⽬中,要留意jvm启动路径。

⽆论该启动路径是位于⽗模块的路径下还是⼦模块的,如果jvm启动路径下不存在
src/main/webapp ⽬录,则 docBase 被设置为C盘下临时的随机⽬录
综上,如果想要依照传统⽅式通过“⽂档基⽬录”去定位⽂档资源(html、css、js),则要确保存在 src/main/webapp ⽬录,即 docBase 不会被设置为随机⽬录;否则,建议直接设置 SpringBoot 将其定位⾄ classpath 下的资源(即 src/main/resource ⽬录下的资源),具体配置如下
1.当不存在 @EnableWebMVC 时
1. SpringBoot 的 @EnableAutoConfiguration 会启⽤⾃动配置类 WebMvcAutoConfiguration,该类配置了⼀些默认的静态资源映射
⾃动映射 localhost:8080/** 为以下路径
classpath:/resources/
classpath:/static/
classpath:/public/
classpath:/META-INF/resources/
⾃动映射 localhost:8080/webjars/** 为以下路径
classpath:/META-INF/resources/webjars/
2. 此时,我们不需要多做什么,只要将静态资源放⼊ src/main/resources ⽬录下的 resources、static 或 public ⽂件夹下,即可通过 url
定位相关资源,例如 localhost:8080/index.html 可定位⾄ src/main/resources/static/index.html
3. 注意:如果编写了以下的⾃定义配置,则以上默认配置将被取消。

更确切的说,⼀旦⾃定义的配置不为空,则默认配置将不被采⽤。

@Configuration
public class GoWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//配置静态资源处理
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/resources2/", "classpath:/static2/",
"classpath:/public2/", "file:///tmp/webapps/");
}
}
如果不喜欢代码配置,也可采取以下属性配置⽅式:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,file:D://hehe
附,有⼀个不常⽤的相关属性如下
//默认值,URL访问采⽤ /**
spring.mvc.static-path-pattern=/**
//URL访问必须采⽤ /pomer/** 的形式
spring.mvc.static-path-pattern=/pomer/**
//URL访问必须采⽤ /12345/** 的形式
spring.mvc.static-path-pattern=/12345/**
2.当存在 @EnableWebMVC 时
1. 如果使⽤了 @EnableWebMvc,则⾃动配置类 WebMvcAutoConfiguration 会失效,因此默认映射路径 /static, /public, META-
INF/resources, /resources 都将失效
2. 这种情况下,只能设置⾃定义配置
⽆任何前缀 -> “⽂档根⽬录”(⼀般指代 src/main/webapp ⽬录),例如 localhost:8080/index.html 定位⾄
src/main/webapp/static/index.html
存在前缀 classpath -> 类路径(⼀般指代 src/main/resources ⽬录)
存在前缀 file:// -> ⽂件系统路径(“绝对路径”)
@Configuration
public class GoWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//配置静态资源处理
registry.addResourceHandler("/**")
.addResourceLocations("resources/", "static/", "public/",
"META-INF/resources/")
.addResourceLocations("classpath:resources/", "classpath:static/", "classpath:public/", "classpath:META-INF/resources/")
.addResourceLocations("file:///tmp/webapps/");
}
}。

相关文档
最新文档