SpringBoot静态资源
Springboot中静态资源该往哪里放:去哪里找?,然而Springboot自动配置源码中寻找答案:WebMvcAutoConfiguration --》addResourceHandlers(静态资源)
从源码中可以知道:静态资源可以放到这些目录下,就可以访问到;
/webjars/**
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
1)、所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
以 webjars:以jar包的方式引入静态资源;
webjars官网:http://www.webjars.org/
<!--引入jquery-webjar-->在访问的时候只需要写webjars下面资源的名称即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
浏览器输入:
localhost:8080/webjars/jquery/3.3.1/jquery.js
2)、"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
官方默认静态资源放到了static目录下,在该目录下写一个index.html即可直接访问,我们还可以在resources目录下创建两个目录,分别是public和resource,这三个目录都可以直接放静态资源,其中访问优先级是resource>static(默认)>public
,这里的templates是模板引擎,就像我们的WEB-INF一样,需要controller的跳转访问
SpringBoot首页
Springboot项目启动默认开启是这样一个页面:
然而我们不想已开启springboot就看到这种页面:
定制首页:
分析源码首页可以放到静态资源目录下都可以自动适配到,也可以放到
在templates目录下,但是需要通过controller来进行跳转,需要模板引擎的支持。Thymeleaf 模板引擎
自定义图标:
配置自己喜欢的图标,(高版本去掉了这个功能,可以降低版本)
@Configuration
@ConditionalOnProperty(
value = {
"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration implements ResourceLoaderAware {
private final ResourceProperties resourceProperties;
private ResourceLoader resourceLoader;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(this.resolveFaviconLocations());
return requestHandler;
}
private List<Resource> resolveFaviconLocations() {
String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
List<Resource> locations = new ArrayList(staticLocations.length + 1);
Stream var10000 = Arrays.stream(staticLocations);
ResourceLoader var10001 = this.resourceLoader;
this.resourceLoader.getClass();
var10000.map(var10001::getResource).forEach(locations::add);
locations.add(new ClassPathResource("/"));
return Collections.unmodifiableList(locations);
}
}
“**/favicon.ico” , 就是图标定义的格式!也是在静态资源文件夹下定义,我们可以自定义来测试一下
自己放一个图标进去,然后在配置文件中关闭SpringBoot默认的图标!
#关闭默认图标
spring.mvc.favicon.enabled=false
清除浏览器缓存,刷新网页,发现图标已经变成自己的了
也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;
spring.resources.static-locations=classpath:/hello/,classpath:/chao/
一旦自己定义了静态文件夹的路径,原来的就都会失效了