SpringBoot-web development (1): import of static resources (source code analysis)



In web development, the most basic item is to import static resources, so how to import static resources in springboot? The answer is in the source code, let's analyze and analyze~

First, press twice shiftto search for the WebMvcAutoConfugureclass in IDEA . This is the auto-configuration class of webMvc. The method for processing springboot static resources is in it.
image-20200921192255315
We slide down and find a webMvc auto-configuration adaptation class. WebMvcAutoConfigurationAdapter
image-20200921192234170
There is a addResourceHandlersmethod, this It is our springboot project to add a method to handle static resources

Let's analyze this code next. We will first parse the orange part of the code, and then parse the blue part of the code, corresponding to the two methods of importing static resources!
image-20200921191250400


Method 1: WebJars

In the addResourceHandlersmethod, the orange code on the icon mentioned one webjarsthing. This is the first way springboot imports static resources. What is this?

if (!registry.hasMappingForPattern("/webjars/**")) {
    
    
   customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
         .addResourceLocations("classpath:/META-INF/resources/webjars/")
         .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

1. What are webjars?

Reference Bowen: https://www.jianshu.com/p/ca568526f0bd https://blog.coding.net/blog/spring-static-resource-process

For usually web开发, we often need to import some static resources, but like js, css, imagesand other static resources management is chaotic version

  • For example Jquery, Bootstrap, Vue.jsother versions of the respective components of the respective front-end frame are different depends

  • Usually we copy these Web resources to the Java directory. This manual copying may cause version errors. If the copy version is wrong, the front-end page cannot be displayed correctly.

So, is there a solution like a back-end management jarpack? This introduces the introduction todayWebJars

  • WebJarsIt provides resource files for Web projects in the form of Jars, and then uses the management of these dependent libraries in Maven to ensure the uniqueness of this Web resource version
  • WebjarsIt is mostly used to Spring Bootcreate microservice projects based on the need to package all resources into executable jars

2. Use of webjars

Regarding WebJarsresources, the official website: https://www.webjars.org/
image-20200921121150290
We go to the website to find the resources we need. Each resource has its own maven coordinates. Add maven dependencies to your project and you can use it directly These resources too.
For example, here, the imported jquerymaven dependency, and the imported jqueryresources can be viewed on the left
image-20200921121830938

3. Webjars structure

Before you start, have a look at Jquerythe webjarsunderstanding under webjarsthe directory structure of the package

META-INF
    └─maven
        └─org.webjars
            └─jquery
                └─pom.properties
                └─pom.xml
    └─resources
        └─webjars
            └─jquery
                └─3.5.1
                       └─(静态文件及源码)

4. Parse the source code

Analyze the following code:

//如果静态资源符合"/webjars/**"的格式
if (!registry.hasMappingForPattern("/webjars/**")) {
    
    
    //添加资源注册到"/webjars/**"
   customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
         .addResourceLocations("classpath:/META-INF/resources/webjars/")
         .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

If the static resource name matches /webjars/**, go to the classpath:/META-INF/resources/webjars/path to search, add the resource to the /webjars/**path, and these two paths are a correspondence:

/webjars/**  --->  classpath:/META-INF/resources/webjars/

In the future, you can directly access the static resources by directly accessing it through the browser through the format of the registration path;

And Webjarsall of our resources conform to this path structure, so we only need to introduce this coordinate through maven, and they can all be found and identified. This is how we import static resources.
image-20200921122039544

5. Test Visit

Next, let's start to test whether we can access static resources. The access format specified in the source code /webjars/**corresponds to the classpath:/META-INF/resources/webjars/**path, here is:

http://localhost:8080/webjars/jquery/3.5.1/jquery.js

You can see the imported jueryjs static file
image-20200921123135697




Method 2: staticPathPattern

In the addResourceHandlersmethod, the blue code on the icon is the second way for springboot to import static resources

1. Source code analysis

//获取staticPathPattern
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//如果静态资源路径符合staticPathPattern的格式
if (!registry.hasMappingForPattern(staticPathPattern)) {
    
    
    customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                         .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                         .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

Similarly, first get it staticPathPattern, and then add resources to register to this path, then what is this path?

We clicked in getStaticPathPattern
image-20200921194643300
and then clicked in and staticPathPattern
image-20200921194714793
found that this path is /**: that is, we /**can access static resources through this format, so what is the real path corresponding to this path?

Click in the code getStaticLocations(), you can see four paths
image-20200921230923841

"classpath:/META-INF/resources/":就是上述的webjars
"classpath:/resources/":reources目录下的resources目录,不存在自己新建
"classpath:/static/":resources目录下的static目录
"classpath:/public/":resources目录下的public目录,不存在自己新建

image-20200921200824407

2. Test visit

For example, we publicput a static file in the directory1.js

hello

image-20200921203423657
Then we started the main program to visit locaohost:8080/1.jsand successfully visited the static resources.
image-20200921203451706
Summary : localhost:8080All the requested static resource paths underneath will be found in those four directories, which are the four directories where static resources are stored.

We can test, when there are multiple static files with the same name exist in different directories above, the priority: resources> static>public




Custom resource path

At addResourceHandlersthe very beginning of the method, there is such a judgment

//如果静态资源已经被自定义
if (!this.resourceProperties.isAddMappings()) {
    
    
    logger.debug("Default resource handling disabled");
    return;
}

You can application.propertiescustomize the path of static resources in the, the default is/**

spring.mvc.static-path-pattern=/zsr/**

It is generally not recommended to do this, and the above method 2 will be invalid (unless explicitly defined as /**)

Guess you like

Origin blog.csdn.net/qq_45173404/article/details/108721839