SpringBoot之静态资源处理

静态资源处理(springboot静态资源映射规则)

   1、第一种方式:spring支持以jar包的方式引入静态资源(webjars)以jQuery为例,导入依赖    网址:https://www.webjars.org/

 1 @Override
 2         public void addResourceHandlers(ResourceHandlerRegistry registry) {
 3             if (!this.resourceProperties.isAddMappings()) {
 4                 logger.debug("Default resource handling disabled");
 5                 return;
 6             }
 7             Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
 8             CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
 9             if (!registry.hasMappingForPattern("/webjars/**")) {
10                 customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
11                         .addResourceLocations("classpath:/META-INF/resources/webjars/")
12                         .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
13             }
14             String staticPathPattern = this.mvcProperties.getStaticPathPattern();
15             if (!registry.hasMappingForPattern(staticPathPattern)) {
16                 customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
17                         .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
18                         .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
19             }
20         }

    所有的/webjars/**,都去 /META-INF/resources/webjars/ 这里面找资源 

1 <!--引入jquery-webjar-->
2         <dependency>
3             <groupId>org.webjars</groupId>
4             <artifactId>jquery</artifactId>
5             <version>3.5.1</version>
6         </dependency>

    然后我们可以访问jquery的静态资源,找到jar包路径   访问路径:localhost:8080/webjars/jquery/3.5.1/jquery.js

  2)、第二种方式:  /** 访问当前项目任何资源 (静态资源文件夹)

1 "classpath:/META-INF/resources/",
2 "classpath:/resources/", 
3 "classpath:/static/", 
4 "classpath:/public/"
5 "/" 当前项目的根路径

  3)、欢迎页;静态资源文件夹下的所有index.html页面;被"/**"映射

    即:localhost:8080/  找index.html页面

  4)、所有的 **/favicon.ico 都在静态资源文件下找

    注意:在springboot2.x版本以前  直接将favicon.ico放到资源文件夹下即可

          在springboot2.x版本以后,需要在每个页面中手动添加

    1)、添加到 thymeleaf模板引擎

<link rel="icon" th:href="@{/favicon.ico}" type="image/x-icon"/>
<link rel="bookmark" th:href="@{/favicon.ico}" type="image/x-icon"/>

    2)、添加到别的模板隐情

1 <link rel="icon" href="/Favicon.ico" type="image/x-icon"/>
3 <link rel="bookmark" href="/Favicon.ico" type="image/x-icon"/>
原文地址:https://www.cnblogs.com/lxy-java/p/12992972.html