Spring Boot(3) Web开发(1)静态资源处理
Spring Boot(3) Web开发(1)静态资源处理
基于spring boot 2.4.3版本
1.静态资源访问
1.1 静态资源目录
把静态资源放在类路径下的以下目录:/static; /public; /resources; /META-INF/resources;这些目录作为这些静态资源的根目录,如输入http://localhost:8080/4.jpg可直接访问
过程:请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面。
1.2静态资源访问前缀
配置访问静态资源路径前缀,如http://localhost:8080/res/2.jpg
spring:mvc:static-path-pattern: /res/**
此时访问需要加上前缀:
注意事项:加上这个后,欢迎页和favicon都会不支持
1.3 修改默认静态资源根路径:
spring:web:resources:static-locations: [classpath:/templates/]
1.4 webjar
自动映射 /webjars/**
引入依赖:
<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.5.1</version></dependency>
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
2.欢迎页与favicon
2.1 欢迎页
本地访问localhost:8080即可访问的页面,即index.html;把该页面放到默认静态资源目录下即可,如果找不到页面,会再找controller是否有/index的映射方法;
2.2 favicon
网站的小图标:
把该图标放在默认静态资源路径即可,名字为favicon.ico
访问效果:
注意不要设置静态资源访问前缀static-path-pattern。
3.静态资源配置原理
3.1 配置静态资源的开始
- 从前面的自动配置原理我们知道,springboot 2.4 在启动时会加载130个场景的组件,即各种xxxAutoConfiguration类,通过@Condition来控制加入的组件;
- 同样,关于静态资源的场景,我们从WebMVCAutoConfiguration开始分析:
- 给容器中配了什么:往下看我们可以看到WebMvcAutoConfigurationAdapter这个类上配置了这些东西:
@Configuration(proxyBeanMethods = false)@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})@EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class, WebProperties.class})@Order(0)public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
其中WebMvcProperties.class和ResourceProperties.class这两个类里面绑定了配置文件:
WebMvcProperties.class ==> @ConfigurationProperties( prefix = "spring.mvc")
ResourceProperties.class ==> @ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false
)
WebProperties.class ==> @ConfigurationProperties("spring.web")
关于静态资源配置的我们用到了前面两个。
- WebMvcAutoConfigurationAdapter只有一个有参构造,有参构造器所有参数的值都会从容器中确定
//有参构造器所有参数的值都会从容器中确定
//ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory Spring的beanFactory
//HttpMessageConverters 找到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
//DispatcherServletPath
//ServletRegistrationBean 给应用注册Servlet、Filter....public WebMvcAutoConfigurationAdapter(WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {this.mvcProperties = mvcProperties;this.beanFactory = beanFactory;this.messageConvertersProvider = messageConvertersProvider;this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();this.dispatcherServletPath = dispatcherServletPath;this.servletRegistrations = servletRegistrations;this.mvcProperties.checkConfiguration();}
3.2 资源处理的默认规则
我们从这个类的addResourceHandlers()方法开始看资源处理的默认规则:
protected void addResourceHandlers(ResourceHandlerRegistry registry) {super.addResourceHandlers(registry);if (!this.resourceProperties.isAddMappings()) {logger.debug("Default resource handling disabled");} else {ServletContext servletContext = this.getServletContext();this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (servletContext != null) {registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});}});}}
打断点:
super.addResourceHandlers(registry):主要是静态资源路径映射;
接下来判断isAddMappings()是否开启,即是否让静态资源路径映射生效,默认是true:
这样,我们可以配置addMapping属性来禁用掉前面的静态资源路径映射规则:
spring:web:resources:add-mappings: false
为false时:
为true时:
addMapping为true会继续往下执行,开始配置静态资源规则:
ServletContext servletContext = this.getServletContext();this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (servletContext != null) {registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});}});
3.2.1 webjars与classpath:/META-INF/resources/webjars/的映射
第一个addResourceHandler()是映射webjars的资源路径到类路径下,点进去:
private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, String... locations) {this.addResourceHandler(registry, pattern, (registration) -> {registration.addResourceLocations(locations);});}
调试可以看到,进入这个方法后,通过一系列的过程将两个路径建立起映射关系;
3.2.2 /**与四个默认静态资源根路径的映射
接下来是第二个addResourceHandler():
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {registration.addResourceLocations(this.resourceProperties.getStaticLocations());if (servletContext != null) {registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});}});
registry的作用跟前面一样,是将两个路径建立起映射关系;
第一个路径:this.mvcProperties.getStaticPathPattern()
从mvcProperties开始,点进去我们可以发现这是WebMvcProperties的一个对象:
所以,我们点进去WebMVCProperties就可以查看getStaticPathPattern()这个get()方法,这个方法与我们普通的get方法区别不大,重点在于构造器如何将staticPathPattern这个属性初始化:
可以看到,无参构造器将staticPathPattern初始化为“/**”;
接下来看映射的路径:
我们关注点在getStaticLocations()这个方法:
可以看到,最终的落脚点在WebProperties类的内部类Resources的CLASSPATH_RESOURCE_LOCATIONS字符串数组中,这个数组的内容:
new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
这就将/**和四个默认路径给映射起来了。
CLASSPATH_RESOURCE_LOCATIONS是常量数组,而staticLocations是变量,而WebProperties对应的配置前缀是@ConfigurationProperties(“spring.web”),所以我们可以来自定义访问路径的前缀:
spring:web:resources:static-locations: [classpath:/templates/]
3.3 欢迎页支持
欢迎页支持主要在这个类中welcomePageHandlerMapping()往容器注入组件
HandlerMapping:能处理哪些请求。
主要关注这一行:
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
点进去new的部分:
可以看到,在欢迎页这里会判断mvcProperties.getStaticPathPattern()是否为“/**”,如果是的话会进行跳转,所以,前面我们加上这个配置后:
spring:mvc:static-path-pattern: /res/**
欢迎页就会失效了。
, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
点进去new的部分:[外链图片转存中...(img-Rb3EfHpg-1616748251081)]可以看到,在欢迎页这里会判断mvcProperties.getStaticPathPattern()是否为“/**”,如果是的话会进行跳转,所以,前面我们加上这个配置后:```yml
spring:mvc:static-path-pattern: /res/**
欢迎页就会失效了。
Spring Boot(3) Web开发(1)静态资源处理相关推荐
- Spring Boot之Web开发
Web开发 简单了解 快速上手 JSON 的支持 RESTful 的支持 支持热部署 快速上手 拦截器与过滤器 自定义过滤器 示例 自定义拦截器 示例 打包部署 多环境配置 服务器配置 项目打包 简单 ...
- Spring Boot与web开发
Spring Boot与web开发 1. 2. 3. 4. 5. 6. 7. 8. 9. 0. 四.Web开发 1.简介 使用SpringBoot: 1).创建SpringBoot应用,选中我们需要的 ...
- Spring Boot:(五)静态资源和拦截器处理
Spring Boot:(五)静态资源和拦截器处理 前言 本章我们来介绍下SpringBoot对静态资源的支持以及很重要的一个类WebMvcConfigurerAdapter. 正文 前面章节我们也有 ...
- Spring Boot(5) web开发(3)拦截器、文件上传、异常处理
Spring Boot(5) web开发(3)拦截器.文件上传.异常处理 学习视频: https://www.bilibili.com/video/BV19K4y1L7MT?p=49&spm_ ...
- 【spring boot】第3篇:spring boot 进行 web 开发
spring boot 对 web 静态资源的管理 经过前两篇文章我们知道spring boot最大的功能就是自动配置.主要是通过以下两个类实现该功能: xxxxAutoConfiguration : ...
- Gradle进阶:1: 结合spring boot进行web开发
在前面的文章中介绍了如何使用gradle的基础知识,这篇文章在某种程度上才是真正意义上的第一个hello world,这里使用一个简单的spring boot的例子,通过gradle进行编译和构建以及 ...
- spring boot 整合web开发之文件上传、静态资源访问、异常处理、返回JSON数据
目录 springboot 整合web开发 返回json数据 静态资源访问 文件上传 全局异常 1.返回json数据 springboot默认的是jackson-databind做为json处理器.也 ...
- Spring Boot与Web开发简介||SpringBoot对静态资源的映射规则
Web开发 1.简介 使用SpringBoot: 1).创建SpringBoot应用,选中我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运 ...
- SpringBoot资料合集-04【Spring Boot与Web开发】
1.SpringMVC快速使用 1.基于restful http接口 的CURD 2.调用rest http接口 3.通过postman调用 4.通过swagger调用 2.SpringMVC自动配置 ...
最新文章
- 第十七篇:信息抽取Information Extraction
- 机器学习 python_送书 | 深入浅出Python机器学习
- Delphi XE2 之 FireMonkey 入门(2)
- leetcode 190 python
- HTML5 Geolocation用来定位用户的位置。
- python库下载哪些_Windows 下各种Python库的下载与安装
- LNMP架构介绍与搭建
- JScript中正则表达函数的说明与应用
- DB2 V10.5 PureScale支持HADR
- BZOJ 2560(子集DP+容斥原理)
- ISO 9001是什么?ISO 9001 质量管理体系详细介绍
- 计算机网络第二章学习通题目及答案
- 基于asp.net806莆田新华网上书店_图书销售系统
- 做图片用的计算机配置文件,电脑如何显示照片色域为DCI-P3标准的拍摄照片
- X86与X64之间的区别
- 前花椒直播CEO胡震生:我如何不花钱引爆的花椒直播
- 【First-order Methods】 5 Smoothness and Strong Convexity
- 2019年了桌面CPU还吊打笔记本CPU?真相了
- 干货分享!杭州知名SEO公司清法网络告诉你如何玩转小红书
- 让自己对bff层有个了解--服务于前端的后端
热门文章
- Android学习之布局管理器嵌套
- Linux下的hostname命令
- inotify java maven_inotifywait + rsync 监控文件并同步
- 调侃面向对象编程的23种设计模式
- html里面css什么意思,Web前端
- java写顾客购买的商品总价格_成交总金额=商品价格×商品件数-总优惠额。 如果一个顾客,购买的商品一口价为5元,购买的商品件数为4,总物流运费4元,满20送3,请问成交的金额是()。...
- java gc日志乱码_gc原理以及gc日志剖析
- Ubuntu 远程管理常用命令
- 实用工具推荐:LICEcap(屏幕录制.gif)
- Zabbix监控Oracle 连接数