Spring Boot自定义静态资源映射
2022-04-17 本文已影响0人
石头耳东
零、本文纲要
- 一、背景
1、Spring Boot项目静态资源默认访问路径
2、在IDEA中对应的路径
3、优先级顺序 - 二、自定义静态资源映射
1、配置文件配置
2、WebMvcConfigurationSupport配置
一、背景
0、基础html页面
注意将不同demo的序号按文件修改即可,demo01.html内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h1>Hello demo01!</h1>
</body>
</html>
1、Spring Boot项目静态资源默认访问路径
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public
2、在IDEA中对应的路径
在IDEA中对应的路径.png
访问方法:http://localhost:8080/demo01.html,如下:
访问方法.png
3、优先级顺序
Ⅰ classpath:/META-INF/resources
→ Ⅱ classpath:/resources
→ Ⅲ classpath:/static
→ Ⅳ classpath:/public
二、自定义静态资源映射
1、配置文件配置
- ① 配置方式
# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默认静态寻址资源路径
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,classpath:/test/
配置文件配置.png
- ② 注意
Ⅰ 此处是覆盖原有配置的,所以默认路径不能漏掉,假设删除原有路径映射,如下:
# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默认静态寻址资源路径
spring.web.resources.static-locations=classpath:/test/
可以看到此时正常访问的为,demo01和demo05,如下:
原有静态映射部分失效.png
注意:如此配置原有配置仅剩 classpath:/META-INF/resources 还生效。
Ⅱ 静态文件请求匹配方式
静态文件请求匹配方式.png
修改后访问路径http://localhost:8080/test/demo05.html,访问如下:
修改后访问.png
2、WebMvcConfigurationSupport配置
- ① 编写静态资源映射类
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/test/**")
.addResourceLocations("classpath:/test/");
}
}
- ② 测试
Java编写配置测试.png
注意:此种配置下,原有的静态资源路径被覆盖、失效。
三、结尾
以上即为Spring Boot自定义静态资源映射的全部内容,感谢阅读。