SpringBoot study notes 4-Web development static resource processing

Crazy God Notes
Video Link

Web development exploration

Introduction
Okay, students, so next, we start to learn SpringBoot and Web development, from this chapter onwards, it belongs to the content of our actual combat part;

In fact, SpringBoot is very simple to use, because the biggest feature of SpringBoot is automatic assembly.

Steps to use SpringBoot:

1. Create a SpringBoot application, select the modules we need, and SpringBoot will automatically configure the modules we need by default

2. Manually configure part of the configuration items in the configuration file to run

3. Focus on writing business code, no need to consider a lot of configuration as before.

To be familiar with the development, you must understand the principle of automatic configuration that you learned before!

For example, what exactly did SpringBoot configure for us? Can we modify it? What configuration can we modify? Can we expand?

Automatically configure components to the container: *** Autoconfiguration

Automatic configuration class, encapsulate the content of the configuration file: ***Properties

Look for the class when it’s okay to see the principle of automatic assembly!

We will then carry out a small project test of a single project, so that everyone can quickly start development!

Static resource processing

Static resource mapping rules
First, we build a normal SpringBoot project and review the HelloWorld program!

Writing a request is very simple. Then we have to introduce our front-end resources. There are many static resources in our project, such as css, js and other files. How to deal with this SpringBoot?

If we are a web application, there will be a webapp under our main. We used to guide all the pages in it, right! But what about our current pom, the packaging method is jar, then can SpringBoot write pages for us in this way? Of course it is possible, but SpringBoot has regulations for the placement of static resources!

Let's talk about this static resource mapping rule first:

In SpringBoot, the web configuration of SpringMVC is in the configuration class of WebMvcAutoConfiguration;

We can go to see there are many configuration methods in WebMvcAutoConfigurationAdapter;

There is a method: addResourceHandlers to add resource processing

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
    if (!this.resourceProperties.isAddMappings()) {
    
    
        // 已禁用默认资源处理
        logger.debug("Default resource handling disabled");
        return;
    }
    // 缓存控制
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    // webjars 配置
    if (!registry.hasMappingForPattern("/webjars/**")) {
    
    
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
    // 静态资源配置
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if (!registry.hasMappingForPattern(staticPathPattern)) {
    
    
        customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                                             .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
}

Read the source code: For example, all /webjars/**, you need to go to classpath:/META-INF/resources/webjars/ to find the corresponding resources;

What are webjars?

The essence of Webjars is to introduce our static resources in the form of jar packages. We had to import a static resource file before and just import it directly.

To use SpringBoot, you need to use Webjars, we can search for it:

Website: https://www.webjars.org
Insert picture description here

To use jQuery, we only need to introduce the pom dependency of the corresponding version of jQuery!


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

Insert picture description here
Access: As long as it is a static resource, SpringBoot will go to the corresponding path to find the resource, we visit here: http://localhost:8080/webjars/jquery/3.6.0/jquery.js
Insert picture description here

The second static resource mapping rule

Then, if we use our own static resources in our project, how should we import them? We look at the next line of code;

We go to staticPathPattern to find the second mapping rule: /**, to access any resource of the current project, it will look for the resourceProperties class, we can click in to see the analysis:


// 进入方法
public String[] getStaticLocations() {
    
    
    return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    
     
    "classpath:/META-INF/resources/",
  "classpath:/resources/", 
    "classpath:/static/", 
    "classpath:/public/" 
};

ResourceProperties can set parameters related to our static resources; it points to the folder where it will look for resources, that is, the contents of the above array.

Therefore, it is concluded that the static resources stored in the following four directories can be identified by us:

"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"

We can create a new corresponding folder in the resources root directory, all of which can store our static files;

For example, if we visit http://localhost:8080/1.js, he will go to these folders to find the corresponding static resource files;

Custom static resource path

We can also specify by ourselves through the configuration file, which folders need us to put static resource files, and configure them in application.properties;

spring.resources.static-locations=classpath:/coding/..,classpath:/zhou/

Once you define the path of the static folder, the original automatic configuration will be invalid!
Insert picture description here

Home Handling

After the static resource folder is finished, let's continue to look down the source code! You can see a mapping of the welcome page, which is our home page!

@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
                                                           FormattingConversionService mvcConversionService,
                                                           ResourceUrlProvider mvcResourceUrlProvider) {
    
    
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // getWelcomePage 获得欢迎页
        this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;
}

Welcome page, all index.html pages under the static resource folder; mapped by /**.

For example, if I visit http://localhost:8080/, I will find index.html under the static resource folder

Create a new index.html, in any of the 3 directories above; then visit the test http://localhost:8080/ to see the result!
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44788518/article/details/114849656