电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

SpringBoot中的靜態資源訪問的實現

瀏覽:17日期:2023-04-25 15:59:02

一、說在前面的話

我們之間介紹過SpringBoot自動配置的原理,基本上是如下:

xxxxAutoConfiguration:幫我們給容器中自動配置組件;xxxxProperties:配置類來封裝配置文件的內容;

二、靜態資源映射規則

1、對哪些目錄映射?

classpath:/META-INF/resources/ classpath:/resources/classpath:/static/ classpath:/public//:當前項目的根路徑

2、什么意思?

就我們在上面五個目錄下放靜態資源(比如:a.js等),可以直接訪問(http://localhost:8080/a.js),類似于以前web項目的webapp下;放到其他目錄下無法被訪問。

3、為什么是那幾個目錄?

3.1、看源碼

我們一起來讀下源碼,這個是SpringBoot自動配置的WebMvcAutoConfiguration.java類來幫我們干的。

@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug('Default resource handling disabled'); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern('/webjars/**')) { customizeResourceHandlerRegistration(registry.addResourceHandler('/webjars/**') .addResourceLocations('classpath:/META-INF/resources/webjars/').setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); }}

3.2、分析源碼

我們重點分析后半截,前半截后面會介紹。

// staticPathPattern是/**String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod));}this.resourceProperties.getStaticLocations()========>ResourcePropertiespublic String[] getStaticLocations() { return this.staticLocations;}========>private String[] staticLocations = RESOURCE_LOCATIONS;========>private static final String[] RESOURCE_LOCATIONS;private static final String[] SERVLET_RESOURCE_LOCATIONS = { '/' };private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 'classpath:/META-INF/resources/', 'classpath:/resources/', 'classpath:/static/', 'classpath:/public/' };========>static { // 可以看到如下是對上面兩個數組進行復制操作到一個新數組上,也就是合并。 RESOURCE_LOCATIONS = new String[CLASSPATH_RESOURCE_LOCATIONS.length + SERVLET_RESOURCE_LOCATIONS.length]; System.arraycopy(SERVLET_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, 0, SERVLET_RESOURCE_LOCATIONS.length); System.arraycopy(CLASSPATH_RESOURCE_LOCATIONS, 0, RESOURCE_LOCATIONS, SERVLET_RESOURCE_LOCATIONS.length, CLASSPATH_RESOURCE_LOCATIONS.length);}所以上述代碼經過我的翻譯后成為了如下樣子:registry.addResourceHandler('/**').addResourceLocations( 'classpath:/META-INF/resources/', 'classpath:/resources/', 'classpath:/static/', 'classpath:/public/', '/') // 設置緩存時間 .setCachePeriod(cachePeriod));

3.3、一句話概括

WebMvcAutoConfiguration類自動為我們注冊了如下目錄為靜態資源目錄,也就是說直接可訪問到資源的目錄。

classpath:/META-INF/resources/ classpath:/resources/classpath:/static/ classpath:/public//:當前項目的根路徑

優先級從上到下。

所以,如果static里面有個index.html,public下面也有個index.html,則優先會加載static下面的index.html,因為優先級!

4、默認首頁

PS:就是直接輸入ip:port/項目名稱默認進入的頁面。

4.1、看源碼

WebMvcAutoConfiguration.java@Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping( ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern());}

4.2、分析源碼

resourceProperties.getWelcomePage()========>public Resource getWelcomePage() { // 遍歷默認靜態資源目錄后面拼接個index.html的數組 // 比如:[/static/index.html, /public/index.html等等] for (String location : getStaticWelcomePageLocations()) { Resource resource = this.resourceLoader.getResource(location); try { if (resource.exists()) {resource.getURL();return resource; } } catch (Exception ex) { // Ignore } } return null;}========>// 下面這段代碼通俗易懂,就是給默認靜態資源目錄后面拼接個index.html并返回,比如:/static/index.htmlprivate String[] getStaticWelcomePageLocations() { String[] result = new String[this.staticLocations.length]; for (int i = 0; i < result.length; i++) { String location = this.staticLocations[i]; if (!location.endsWith('/')) { location = location + '/'; } result[i] = location + 'index.html'; } return result;}

所以上述代碼經過我的翻譯后成為了如下樣子:

return new WelcomePageHandlerMapping( 'classpath:/META-INF/resources/index.html', 'classpath:/resources/index.html', 'classpath:/static/index.html', 'classpath:/public/index.html', '/index.html' , '/**');

4.3、一句話概括

WebMvcAutoConfiguration類自動為我們注冊了如下文件為默認首頁。

classpath:/META-INF/resources/index.htmlclasspath:/resources/index.htmlclasspath:/static/index.html classpath:/public/index.html/index.html

優先級從上到下。

所以,如果static里面有個index.html,public下面也有個index.html,則優先會加載static下面的index.html,因為優先級!

5、favicon.ico

PS:就是SpringBoot中的靜態資源訪問的實現這個圖標。

5.1、看源碼

@Configuration@ConditionalOnProperty(value = 'spring.mvc.favicon.enabled', matchIfMissing = true)public static class FaviconConfiguration { private final ResourceProperties resourceProperties; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); mapping.setUrlMap(Collections.singletonMap('**/favicon.ico', faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler .setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; }}

5.2、分析源碼

// 首先可以看到的是可以設置是否生效,通過參數spring.mvc.favicon.enabled來配置,若無此參數,則默認是生效的。@ConditionalOnProperty(value = 'spring.mvc.favicon.enabled', matchIfMissing = true)========》// 可以看到所有的**/favicon.ico都是在faviconRequestHandler()這個方法里找。mapping.setUrlMap(Collections.singletonMap('**/favicon.ico', faviconRequestHandler()));========》faviconRequestHandler().this.resourceProperties.getFaviconLocations()// 就是之前的五個靜態資源文件夾。 List<Resource> getFaviconLocations() { List<Resource> locations = new ArrayList<Resource>( this.staticLocations.length + 1); if (this.resourceLoader != null) { for (String location : this.staticLocations) { locations.add(this.resourceLoader.getResource(location)); } } locations.add(new ClassPathResource('/')); return Collections.unmodifiableList(locations);}

5.3、一句話概括

只要把favicon.ico放到如下目錄下,就會自動生效。

classpath:/META-INF/resources/ classpath:/resources/classpath:/static/ classpath:/public//:當前項目的根路徑

6、webjars

6.1、看源碼

WebMvcAutoConfiguration@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug('Default resource handling disabled'); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern('/webjars/**')) { customizeResourceHandlerRegistration(registry.addResourceHandler('/webjars/**') .addResourceLocations('classpath:/META-INF/resources/webjars/').setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); }}

6.2、分析源碼

這次我們來分析前半截。

Integer cachePeriod = this.resourceProperties.getCachePeriod();if (!registry.hasMappingForPattern('/webjars/**')) { customizeResourceHandlerRegistration( registry.addResourceHandler('/webjars/**') .addResourceLocations( 'classpath:/META-INF/resources/webjars/') .setCachePeriod(cachePeriod));}

6.3、一句話概括

所有/webjars/**都從classpath:/META-INF/resources/webjars/路徑下去找對應的靜態資源。

6.4、什么是webjars?

就是以jar包的方式引入靜態資源。

官網地址:http://www.webjars.org/。類似于maven倉庫。

SpringBoot中的靜態資源訪問的實現

我們可以做個例子,將jquery引入到項目中

<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version></dependency>

看項目依賴

SpringBoot中的靜態資源訪問的實現

會自動為我們引入jquery,要怎么使用呢?我們上面說過:

所有/webjars/*都從classpath:/META-INF/resources/webjars/路徑下去找對應的靜態資源。

所以我們啟動項目,訪問:http://localhost:8080/webjars/jquery/3.3.1/jquery.js即可。

必須在這幾個路徑下SpringBoot才會掃描到!

'classpath:/META-INF/resources/', 'classpath:/resources/','classpath:/static/', 'classpath:/public/' '/':當前項目的根路徑

SpringBoot中的靜態資源訪問的實現

到此這篇關于SpringBoot中的靜態資源訪問的實現的文章就介紹到這了,更多相關SpringBoot 靜態資源訪問內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 劳动法网-专业的劳动法和劳动争议仲裁服务网 | 涂层测厚仪_光泽度仪_uv能量计_紫外辐照计_太阳膜测试仪_透光率仪-林上科技 | 苗木价格-苗木批发-沭阳苗木基地-沭阳花木-长之鸿园林苗木场 | 专注氟塑料泵_衬氟泵_磁力泵_卧龙泵阀_化工泵专业品牌 - 梭川泵阀 | 环压强度试验机-拉链拉力试验机-上海倾技仪器仪表科技有限公司 | 硬度计,金相磨抛机_厂家-莱州华煜众信试验仪器有限公司 | 电缆接头_防水接头_电缆防水接头 - 乐清市新豪电气有限公司 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 欧美日韩国产一区二区三区不_久久久久国产精品无码不卡_亚洲欧洲美洲无码精品AV_精品一区美女视频_日韩黄色性爱一级视频_日本五十路人妻斩_国产99视频免费精品是看4_亚洲中文字幕无码一二三四区_国产小萍萍挤奶喷奶水_亚洲另类精品无码在线一区 | 威廉希尔WilliamHill·足球(中国)体育官方网站 | LOGO设计_品牌设计_VI设计 - 特创易 | 筒瓦厂家-仿古瓦-寺庙-古建琉璃瓦-宜兴市古典园林建筑陶瓷厂有限公司 | 游动电流仪-流通式浊度分析仪-杰普仪器(上海)有限公司 | 北京宣传片拍摄_产品宣传片拍摄_宣传片制作公司-现像传媒 | 贝朗斯动力商城(BRCPOWER.COM) - 买叉车蓄电池上贝朗斯商城,价格更超值,品质有保障! | 镀锌方管,无缝方管,伸缩套管,方矩管_山东重鑫致胜金属制品有限公司 | 艺术涂料|木纹漆施工|稻草漆厂家|马来漆|石桦奴|水泥漆|选加河南天工涂料 | 钢衬四氟管道_钢衬四氟直管_聚四氟乙烯衬里管件_聚四氟乙烯衬里管道-沧州汇霖管道科技有限公司 | 玄米影院| b2b网站大全,b2b网站排名,找b2b网站就上地球网 | CE认证_产品欧盟ROHS-REACH检测机构-商通检测 | 家庭教育吧-在线家庭教育平台,专注青少年家庭教育 | 水厂自动化|污水处理中控系统|水利信息化|智慧水务|智慧农业-山东德艾自动化科技有限公司 | 成都亚克力制品,PVC板,双色板雕刻加工,亚克力门牌,亚克力标牌,水晶字雕刻制作-零贰捌广告 | 山东成考网-山东成人高考网| 仓储笼_仓储货架_南京货架_仓储货架厂家_南京货架价格低-南京一品仓储设备制造公司 | 上海新光明泵业制造有限公司-电动隔膜泵,气动隔膜泵,卧式|立式离心泵厂家 | 精密模具加工制造 - 富东懿 | 博医通医疗器械互联网供应链服务平台_博医通| 网站建设-临朐爱采购-抖音运营-山东兆通网络科技 | 光环国际-新三板公司_股票代码:838504 | 深圳离婚律师咨询「在线免费」华荣深圳婚姻律师事务所专办离婚纠纷案件 | 华夏医界网_民营医疗产业信息平台_民营医院营销管理培训 | 包装设计公司,产品包装设计|包装制作,包装盒定制厂家-汇包装【官方网站】 | 老城街小面官网_正宗重庆小面加盟技术培训_特色面馆加盟|牛肉拉面|招商加盟代理费用多少钱 | 有机肥设备生产制造厂家,BB掺混肥搅拌机、复合肥设备生产线,有机肥料全部加工设备多少钱,对辊挤压造粒机,有机肥造粒设备 -- 郑州程翔重工机械有限公司 | 南京蜂窝纸箱_南京木托盘_南京纸托盘-南京博恒包装有限公司 | 无锡网站建设_企业网站定制-网站制作公司-阿凡达网络 | 交变/复合盐雾试验箱-高低温冲击试验箱_安奈设备产品供应杭州/江苏南京/安徽马鞍山合肥等全国各地 | 量子管通环-自清洗过滤器-全自动反冲洗过滤器-沼河浸过滤器 | CPSE安博会|