SpringBoot: Web development static resource processing

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 need 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

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 through the configuration file ourselves, which folders need us to put static resource files, and configure them in application.properties;

spring.resources.static-locations=classpath:/coding/,classpath:/kuang/
Once you define the path of the static folder, the original automatic configuration will be invalid!

Home Handling

@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;
}

Click in to continue watching

private Optional<Resource> getWelcomePage() {
    
    
    String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
    // ::是java8 中新引入的运算符
    // Class::function的时候function是属于Class的,应该是静态方法。
    // this::function的funtion是属于这个对象的。
    // 简而言之,就是一种语法糖而已,是一种简写
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
// 欢迎页就是一个location下的的 index.html 而已
private Resource getIndexHtml(String location) {
    
    
    return this.resourceLoader.getResource(location + "index.html");
}

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!

Guess you like

Origin blog.csdn.net/david2000999/article/details/114481663