springboot --Web开发静态资源处理
1.静态资源处理
1.1静态资源映射规则
springboot中, SpringMVC的web配置都在WebMvcAutoConfiguration 这个配置类中,addResourceHandlers添加资源处理
1.1.1webjars
webjars 本质是jar包的方式引入我们的静态资源,使用springboot需要使用webjars,
网站:https://www.webjars.org
案例:使用jQuery,只需要引入对应的版本依赖
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
案例: 使用swagger UI
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.49.0</version>
</dependency>
1.1.2创建项目
使用步骤:
1.创建一个springboot项目
2.导入jQuery的依赖
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
3.查看是否导入依赖
4.访问静态资源:http://localhost:8080/webjars/jquery/3.6.0/jquery.js
5.测试成功
1.2 第二种静态资源映射的规则
项目中的静态资源怎么导入?
在WebMVCConfiguration 中方法:addResourceHandlers 还有一个:staticPathPattern 第二种映射规则:“ /**”,访问当前的项目任意资源,它会去找 resourceProperties 这个类
总结:
ResourceProperties 可以设置和我们静态资源有关的参数:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" };
所有我们把静态资源放在这些目录下,自动去找。
1.3自定义一个静态资源路径
在application.yml 配置
spring:
web:
resources:
static-locations: classpath=/JJ,classpath:Lxx
所有的自动装配的配置都会失效!
2.首页处理
2.1源码分析
2.1.1分析步骤
首页全局搜索:WelcomePageHandlerMapping
进入WelcomePageHandlerMapping:
总结:静态资源文件夹下的index.html,被“/**”映射。
就是我们访问http://localhsot:8080, 默认访问的是index的html的页面
2.2 关于网站的图标的说明
Spring Boot在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。
1.关闭Springboot默认的图标
2.自己使用logo
3.清除浏览器的缓冲,刷新网页