table of Contents
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 shift
to search for the WebMvcAutoConfugure
class in IDEA . This is the auto-configuration class of webMvc. The method for processing springboot static resources is in it.
We slide down and find a webMvc auto-configuration adaptation class. WebMvcAutoConfigurationAdapter
There is a addResourceHandlers
method, 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!
Method 1: WebJars
In the
addResourceHandlers
method, the orange code on the icon mentioned onewebjars
thing. 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 likejs
,css
,images
and other static resources management is chaotic version
For example
Jquery
,Bootstrap
,Vue.js
other versions of the respective components of the respective front-end frame are different dependsUsually 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
jar
pack? This introduces the introduction todayWebJars
WebJars
It 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 versionWebjars
It is mostly used toSpring Boot
create microservice projects based on the need to package all resources into executable jars
2. Use of webjars
Regarding WebJars
resources, the official website: https://www.webjars.org/
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 jquery
maven dependency, and the imported jquery
resources can be viewed on the left
3. Webjars structure
Before you start, have a look at
Jquery
thewebjars
understanding underwebjars
the 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 Webjars
all 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.
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 juery
js static file
Method 2: staticPathPattern
In the
addResourceHandlers
method, 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
and then clicked in and staticPathPattern
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
"classpath:/META-INF/resources/":就是上述的webjars
"classpath:/resources/":reources目录下的resources目录,不存在自己新建
"classpath:/static/":resources目录下的static目录
"classpath:/public/":resources目录下的public目录,不存在自己新建
2. Test visit
For example, we public
put a static file in the directory1.js
hello
Then we started the main program to visit locaohost:8080/1.js
and successfully visited the static resources.
Summary : localhost:8080
All 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
addResourceHandlers
the very beginning of the method, there is such a judgment
//如果静态资源已经被自定义
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
You can application.properties
customize 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 /**
)