Spring boot学习 (九) 之静态资源的学习
前言
在上一篇学拦截器的时候我们自定义配置类的时候有实现一个非常重要的接口 :WebMvcConfigurer
,这次我们继续用这个类来学习spring-boot
的静态资源处理。Spring-boot
默认提供了静态资源处理,使用WebMvcAutoConfiguration
配置各种属性。没有特殊的要求建议大家使用默认配置。
正文
一,默认的资源映射
spring-boot默认配置的资源映射有下面几种:
/META-INF/resources
/resources
/static
-
/public
他们都在classpath:
目录下,如/static在工程中的目录为src/main/resources/static
。默认配置的/**
映射到/static
(或/public、/resources、/META-INF/resources
),
目录这么多那么他们的优先级顺序是怎么样的呢?大家可以像我一样在不同的目录下面放同一个index.html
,html
文件里面的内容不同:
启动项目访问:http://localhost:8080/index.html

会发现优先级最高的是:
/META-INF/resources
。经测试他们的优先级顺序为:META/resources > resources > static > public
二,自定义资源映射
上面介绍的是几种的是spring-boot默认的资源映射,在一般的情况下我们就使用默认的配置即可。当然我们也是可以自定义资源映射的,下面介绍几种不同情况的自定义方式。
1,自定义目录(这里用到了WebMvcConfigurer
接口)
实现WebMvcConfigurer
接口,并重写addResourceHandlers
方法,在里面自定目录,代码如下:
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mlin/**").addResourceLocations("classpath:/mlin/");
}
}
访问mlin
文件夹中的index.html
图片的地址为 http://localhost:8080/mlin/index.html
如果将/mlin/**
改成/**
就表示覆盖系统的默认配置,当访问: http://localhost:8080/index.html会访问到classpath:/mlin/
下面的资源而不是原先的/META-INF/resources
下面的资源了。
可以多次使用 addResourceLocations
添加目录,优先级先添加的高于后添加的。
registry.addResourceHandler("/**").addResourceLocations("classpath:/mlin/").addResourceLocations("classpath:/static/");
还可以写成:
registry.addResourceHandler("/**").addResourceLocations("classpath:/mlin1/", "classpath:/mlin2/", "classpath:/mlin3/");
注:自定义目录映射,不影响Spring Boot的默认映射。
2,使用外部目录
使用外部目录很简单,只要在路径记得加file:
,再指定绝对路径即可:
registry.addResourceHandler("/mlin/**").addResourceLocations("file:C:/test/");
3,通过配置文件配置
spring-boot
也为我们提供了可以直接在 application.properties(或.yml)
中配置的方法:
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=
- 当
spring.mvc.static-path-pattern=/mlin/**
而spring.resources.static-locations=
表示:
想访问classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
下面的资源index.html
时,访问路径为:http://localhost:8080/mlin/index.html ,而不是之前的 http://localhost:8080/index.html - 当
spring.mvc.static-path-pattern=/mlin/**
而spring.resources.static-locations=/mlin/
表示:
访问路径为:http://localhost:8080/mlin/index.html 和访问路径为:http://localhost:8080/index.html访问的都是classpath:/mlin/
下面的index.html
原创作者:梦凌小样
作品链接:https://www.jianshu.com/p/84f66aa9b17d【原创不易,转载请注明出处,感谢理解】
一位爱生活,爱创作,爱分享,爱自己的90后女程序员一枚,记录工作中的点点滴滴,一起学习,共同进步,期待能和优秀的您交上朋友