日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot_web开发-webjars静态资源映射规则

發(fā)布時間:2024/4/13 javascript 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot_web开发-webjars静态资源映射规则 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
現(xiàn)在要做WEB功能,還是選擇WEB模塊,pom文件依賴web模塊,<dependency><!-- 引入web模塊 --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency>resources配置文件,現(xiàn)在我先來寫上一個HelloWorld 頁面來發(fā)hello請求,返回一個helloworld字符串,我們來體驗一下web的快速開發(fā),有了springboot以后,我就選完模塊以后,我們是不是什么都沒配,我們就直接來寫就行了,我們來處理hello請求,只是HelloWorld要寫出去要加上@ResponseBody,以前的MVC都不用配了,直接來用,來測試一下這個Hello,看能不能訪問,他這里說服務器8080端口已經(jīng)啟動,我們來訪問一下http://localhost:8080/helloHelloWorld沒問題 package com.learn.controller;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController;@RestController public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello() {return "hello";} } package com.learn;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @SpringBootApplication 來標注一個主程序類,說明這是一個Sprint Boot應用* @author Leon.Sun**/ //@ImportResource(locations= {"classpath:beans.xml"}) @SpringBootApplication public class SpringBoot02ConfigApplication {public static void main(String[] args) {// Spring應用啟動起來SpringApplication.run(SpringBoot02ConfigApplication.class,args);} } 直接就用就行了,接下來我們來做我們這個實驗,如果我們現(xiàn)在是一個WEB應用,那我們main下會有一個webapp文件夾,那我們將所有的頁面,全都是導在這的,大家來看,現(xiàn)我們的pom是打成jar的方式,能不能給我們寫頁面,這也是可以的,只不過我們的CSS文件要放哪,我們SpringBoot有規(guī)定,SpringBoot對靜態(tài)資源的映射規(guī)則,這映射規(guī)則我們首先來看,第一種規(guī)則,在咱們SpringBoot里面呢,SpringMVC的相關配置,都在WebMvcAutoConfiguration里邊,而這個配置里邊呢,我們來從頭往下看,多的東西我們就不看了,下邊有一個addResourceHandlers@Override public 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));} }添加資源映射,我們后來還會用到這個原理,用到的時候再來仔細講這個原理,只不過我們來看這個關鍵字,添加咱們的資源映射,第一個規(guī)則"/webjars/**",所有"/webjars/"路徑訪問,訪問都去哪找資源呢,這里有映射請求,webjars下的所有請求,都去這一塊來找資源,都去"classpath:/META-INF/resources/webjars/"這里找資源,而什么是webjars呢,webjars簡單來說,是以jar包的方式引入資源的,以前我們要導入jquery什么,那么我們有一個webapp的文件夾,我們把頁面,script src就能引了,但是現(xiàn)在我們有一個webjars,可以用jar包的方式,我們來搜索一下,https://www.webjars.org這個網(wǎng)站,就來參考他,將我們的前端框架,jquery,bootstrap,他們可以以maven依賴的方式,交給我們,這樣我們要用的話就簡單多了,你在這就可以拿過來,我把jquery引進來<dependency><groupId>org.webjars</groupId><artifactId>jquery</artifactId><version>3.4.1</version> </dependency>只要引入jquery的webjar,讓他來自動下載,來看一下jquery的webjar長什么樣呢,D:\app\repository\org\webjars\jquery\3.3.1\jquery-3.3.1.jar注意來看,這里有META-INF,有resources目錄,下邊有webjar,jquery,有些是目錄合起來了,這個跟我們剛才說的映射規(guī)則是一樣的

這樣的話正好對應這個映射,localhost:8080/webjars/abcwebjars下的任意請求,這個資源去哪找呢,都去這個文件夾,META-INF,resources,webjars,我們webjars沒有abc,所以找不到,我們就要jquerylocalhost:8080/webjars/jquery/3.3.1/jquery.jsjquery下的3.3.1,jquery.js,就是這個訪問路徑,我們試一下這個訪問路徑能不能訪問到,我們把項目重啟一下,我來訪問http://localhost:8080/webjars/jquery/3.3.1/jquery.js我們發(fā)現(xiàn)js是能訪問的,以后我們用webjars,訪問公用的樣式,那就簡單多了,你要做的就是引入依賴就行了,我們在這引入依賴,我們boot都幫你設置好了,訪問的時候只要寫webjars資源的名字就行了,在訪問的時候,只需要寫webjars下的資源即可,我們要用webjars我們就可以這樣來用,但是如果是我們自己的呢,@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties implements ResourceLoaderAware, InitializingBean {我們在設置項里邊,主要有這么幾個,一個是ResourceProperties,可以設置與資源有關的參數(shù),主要是我們的靜態(tài)資源,例如我們的緩存時間,除了webjars,下邊還有一個if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); }registry添加資源映射,/*** Path pattern used for static resources.*/ private String staticPathPattern = "/**";那就是第二種映射規(guī)則,你訪問任何路徑,訪問當前項目的任何資源,private static final String[] RESOURCE_LOCATIONS;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); }靜態(tài)代碼塊,new了一個數(shù)組,private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/", "classpath:/public/" };他會去這幾個文件夾下,一個是類路徑下的resources,classpath:/META-INF/resources/,classpath:/static/,還有當前項目的根路徑,private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" };這幾個文件夾就稱為靜態(tài)資源,靜態(tài)資源的文件夾,你把你的靜態(tài)資源保存在這幾個文件夾里面,都會來這幾個文件夾里找內(nèi)容

第一個是類路徑下的META-INF,建立resources,resources是類路徑的根目錄,我在他的下邊再創(chuàng)建一個resources,第三個是建立static,第四個是public,這幾個路徑都可以來存放靜態(tài)資源,訪問是沒問題的,我把他都放在static目錄下,要怎么訪問呢,你來訪問項目下的任何東西,localhost:8080/abc你要訪問abc,如果沒人處理,默認去這些路徑下的靜態(tài)資源,去靜態(tài)資源文件夾里找abc,我們當然不訪問abc,我來訪問一個能用的,這是靜態(tài)資源文件夾,不用加靜態(tài)資源文件夾的名,本來就從他下面找的,localhost:8080/image/1.png我們發(fā)現(xiàn)也是能訪問的,所以這幾個目錄大家注意

在這個自動配置里邊,@Bean public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),this.mvcProperties.getStaticPathPattern()); }這里翻譯過來叫做歡迎頁的映射,歡迎頁是什么呢,其實就是我們的首頁,配置歡迎頁映射,我們先不管HandlerMapping,我們先來看一下它是怎么映射的呢,HandlerMapping其實是我們SpringMVC最底層的組件,他來保存每一個請求誰來處理,getWelcomePage獲取到歡迎頁,public Resource getWelcomePage() {for (String location : getStaticWelcomePageLocations()) {Resource resource = this.resourceLoader.getResource(location);try {if (resource.exists()) {resource.getURL();return resource;}}catch (Exception ex) {// Ignore}}return null; }從getStaticWelcomePageLocations這里挨個遍歷,因為歡迎頁挺多的,private 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; }這還是靜態(tài)文件夾staticLocations,這個靜態(tài)文件夾拼了index.html,歡迎頁它是怎么設置的呢,靜態(tài)文件夾下的,所有index.html頁面,他這里還配了getStaticPathPattern,被誰映射,/*** Path pattern used for static resources.*/ private String staticPathPattern = "/**";不就是被"/**"映射,反過來就是說,我來訪問當前項目,比如我來訪問localhost,localhost:8080/我就訪問當前項目,我沒有指定路徑,因為他也滿足"/**",靜態(tài)資源下的index.html,找index頁面,那我們來試一下是不是這個效果呢,默認我來訪問8080,這是一個404,沒有什么首頁,我想要訪問怎么訪問呢,比如我把首頁放在public文件夾下,我就來放一個index.html,我們就來寫一個首頁,我來運行一下,默認首頁就過來了,所以他做了首頁映射

喜歡的圖標是什么呢,配置喜歡的圖標,@Configuration @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration {private final ResourceProperties resourceProperties;public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;}@Beanpublic SimpleUrlHandlerMapping faviconHandlerMapping() {SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",faviconRequestHandler()));return mapping;}@Beanpublic ResourceHttpRequestHandler faviconRequestHandler() {ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();requestHandler.setLocations(this.resourceProperties.getFaviconLocations());return requestHandler;}}每個頁面訪問的時候,都會有一個圖標,那我們也能用我們的圖標,你可以用spring.mvc.favicon.enabled這個配置來啟用,即使你不配他也是啟用的,他怎么放呢,我們就看"**/favicon.ico"這個關鍵字,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); }我們喜歡的圖標路徑,還是靜態(tài)文件夾staticLocations,所有的"**/favicon.ico"這個都是在靜態(tài)文件夾下找,我們要做我們的圖標了,你不管是訪問任意層路徑下的他,圖標都是在我們靜態(tài)文件夾下找,我就把我們的圖標我也拿來,你不管那個頁面下要用這個圖標,都能在靜態(tài)資源文件夾下找,圖標就變過來了,這就是springboot默認的做的幾個資源映射,主要是有這么幾個靜態(tài)資源文件夾,這幾個靜態(tài)文件夾以后就來放東西就行了,而且它是能夠配置的,我們一直用的是staticLocations,這個staticLocations呢,其實是ResourceProperties下的注解,我們想改變靜態(tài)文件夾下的路徑,@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties implements ResourceLoaderAware, InitializingBean {spring.resources.static-locations=classpath:/hello,classpath:/learn我給他配置類路徑下的hello文件夾,如果多個配置,我們就逗號分隔,因為這個東西是一個數(shù)組,數(shù)組我們用逗號分割就行了,learn文件夾,這樣你定義了幾個文件夾,再來啟動一下,你前面的靜態(tài)資源還能不能訪問呢,我們發(fā)現(xiàn)就不行了localhost:8080/因為我們自己定義了靜態(tài)文件夾的文件,我就把它注釋掉,我們就不定義了,這就是Springboot對靜態(tài)資源的映射處理 #debug=true #server.port=8081#server.context-path=/boot02spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=truelogging.level.com.learn=trace #logging.file=D:/springboot.log logging.file=springboot.log #logging.path=/spring/log logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n logging.pattern.file=%d{yyyy-MM-dd} ==== [%thread] %-5level ==== %logger{50} ==== %msg%n #spring.resources.static-locations=classpath:/hello,classpath:/learn

?

總結

以上是生活随笔為你收集整理的SpringBoot_web开发-webjars静态资源映射规则的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。