In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares with you is an example analysis of the priority of loading order of static resources in springboot. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Springboot static resource loading order priority
Look inside the springboot source code.
Springboot static resource loading rules
We often use springboot to create web applications. How are gold static resources stored in springboot?
I. static resource mapping rules
Let's first create a springboot project. Use https://start.spring.io/ idea built-in to create a project, not much to say.
We want to introduce our front-end resources, our project has a lot of static resources, such as css,js and other files, we used to write
The project and all create their own folders and design their own access paths, but now, how to deal with this SpringBoot?
If we were a web application, we would have a webapp under our main. We used to guide all the pages in the
It's in here, right! But our current pom is packaged in a jar way, so this way
Can SpringBoot come and write a page for us? Yes, of course, but SpringBoot has its own set of rules for the location of static resources!
In SpringBoot, the web configuration of SpringMVC is all in the configuration class WebMvcAutoConfiguration. We can see that there are many configuration methods in WebMvcAutoConfigurationAdapter. There is one method: addResourceHandlers adds resource processing.
Public void addResourceHandlers (ResourceHandlerRegistry registry) {/ / static resource not found in default configuration if (! this.resourceProperties.isAddMappings ()) {/ / default resource processing logger.debug ("Default resource handling disabled") has been disabled;} else {Duration cachePeriod = this.resourceProperties.getCache (). GetPeriod (); CacheControl cacheControl = this.resourceProperties.getCache (). GetCachecontrol (). ToHttpCacheControl () / / webjars maven introduces static resource if (! registry.hasMappingForPattern ("/ webjars/**")) {this.customizeResourceHandlerRegistration (registry.addResourceHandler (new String [] {"/ webjars/**"}) .addResourceLocations (new String [] {"classpath:/META-INF/resources/webjars/"}) .setCachePeriod (this.getSeconds (cachePeriod)) .setCacheControl (cacheControl));} String staticPathPattern = this.mvcProperties.getStaticPathPattern () If (! registry.hasMappingForPattern (staticPathPattern)) {this.customizeResourceHandlerRegistration (registry.addResourceHandler (new String [] {staticPathPattern}) .addResourceLocations (WebMvcAutoConfiguration.getResourceLocations (this.resourceProperties.getStaticLocations () .setCachePeriod (this.getSeconds (cachePeriod)) .setCacheControl (cacheControl));}} 1.webjars
The essence of Webjars is to introduce our static resources in the way of jar package. We used to import a static resource file and import it directly.
To use SpringBoot, you need to use Webjars, so we can search for it:
Website: https://www.webjars.org
To use jQuery, we just need to introduce the pom dependency of the corresponding version of jQuery!
When we open the website, we can see that there are many maven introductions of front-end js components below.
Org.webjars jquery 3.4.1
Put this introduction into the pom.xml file, and you can see the jquery introduction in the mavenjar package.
Start project access: http://localhost:8080/webjars/jquery/3.4.1/jquery.js to see jquery.js
2.springboot built-in default access path
In the WebMvcAutoConfiguration mvc core class component, let's take a look at the following line of code. Let's go to staticPathPattern and find the second mapping rule: / * *. If you visit any resource of the current project, it will go to the resourceProperties class. We can click into it and take a look at it:
String staticPathPattern = this.mvcProperties.getStaticPathPattern (); if (! registry.hasMappingForPattern (staticPathPattern)) {this.customizeResourceHandlerRegistration (registry.addResourceHandler (new String [] {staticPathPattern}) .addResourceLocations (WebMvcAutoConfiguration.getResourceLocations (this.resourceProperties.getStaticLocations () .setCachePeriod (this.getSeconds (cachePeriod)) .setCacheControl (cacheControl));}
ResourceProperties can set parameters related to our static resources; this points to the folder where it will look for resources, that is, the contents of the array above.
So: the static resources stored in the following four directories can be identified by us:
1. "classpath:/META-INF/resources/"
2. "classpath:/resources/"
3. "classpath:/static/"
4. "classpath:/public/"
Private static final String [] CLASSPATH_RESOURCE_LOCATIONS = new String [] {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"}; private String [] staticLocations; private boolean addMappings; private final ResourceProperties.Chain chain; private final ResourceProperties.Cache cache; public ResourceProperties () {this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS; this.addMappings = true This.chain = new ResourceProperties.Chain (); this.cache = new ResourceProperties.Cache ();} public String [] getStaticLocations () {return this.staticLocations;}
We can create a new folder under the resources root directory, and we can store our static files.
For example, if we visit http://localhost:8080/test.js, he will look for the corresponding static resource files in these folders.
Create a test.js file under each of the four directories, and let's test it separately.
All four directories have test.js, and we found that loading the files under the resourse is a priority.
Delete the test.js under resourse, check it again, and find that the files under static are loaded.
Again, delete the file under static and try it: public executed
Finally, delete the files under public:
We can find that springboot loads static resource files with the following priority: resourse > static > public > META-INF
We can also specify which folders we need to put static resource files through the configuration file, which can be configured in application.properties.
Spring.resources.static-locations=classpath:/coding/,classpath:/cpown/
Once you have defined the path of the static folder, the original automatic configuration will be invalid!
3. Home page processing @ Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping (ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping (new TemplateAvailabilityProviders (applicationContext), applicationContext, this.getWelcomePage (), this.mvcProperties.getStaticPathPattern ()); welcomePageHandlerMapping.setInterceptors (this.getInterceptors (mvcConversionService, mvcResourceUrlProvider)); welcomePageHandlerMapping.setCorsConfigurations (this.getCorsConfigurations ()); return welcomePageHandlerMapping;} private Optional getWelcomePage () {String [] locations = WebMvcAutoConfiguration.getResourceLocations (this.resourceProperties.getStaticLocations ()) Return Arrays.stream (locations) .map (this::getIndexHtml) .filter (this::isReadable). FindFirst ();} private Resource getIndexHtml (String location) {return this.resourceLoader.getResource (location + "index.html");}
This is to load the default welcome page, all index.html pages under the static resource folder; mapped by / * *.
For example, when I visit http://localhost:8080/, I will find the index.html under the static resource folder.
Create a new index.html, any of our three directories above, and then visit the test http://localhost:8080/ to see the results!
4. Website icon
Like other static resources, Spring Boot looks for favicon.ico in the configured static content location. If such a file exists, it is automatically used as the favicon of the application.
1. Turn off the default icon of SpringBoot
# turn off the default icon spring.mvc.favicon.enabled=false
2. Put an icon in the static resources directory and I put it in the public directory
3. Clear browser cache! Refresh the page and find that the icon has become your own!
The above is an example analysis of the priority of static resource loading order in springboot. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.