springboot-crazy-06-(Web development static resource processing)

6. SpringBoot: static resource handling for Web development

Research on Web Development

10.1 introduction

OK, students, next, let's start to learn about SpringBoot and Web development. From this chapter, it will belong to our actual combat part;

In fact, the things of SpringBoot are 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 some configuration items in the configuration file to run

3. Focus on writing business code without considering a lot of configurations like before.

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

For example, what does SpringBoot configure for us? Can we change it? What configurations can we modify? Can we expand?

  • Automatically configure components into containers: * * * Autoconfiguration
  • Automatic configuration class, encapsulating the contents of the configuration file: * * * Properties

If you have nothing to do, look for the class and see the principle of automatic assembly!

After that, we will conduct a small project test of a single project, so that we can start the development quickly!

Static resource processing

10.2. Static resource mapping rules

First, let's build an ordinary SpringBoot project and review the HelloWorld program!

Writing a request is very simple. 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 import all pages here, right! But our current pom is packaged as jar. Can SpringBoot write pages for us in this way? Of course, it is possible, but SpringBoot has regulations on the location of static resources!

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

In spring boot, the web configuration of spring MVC is in the configuration class webmvcoautoconfiguration;

We can see that there are many configuration methods in webmvca autoconfigurationadapter;

There is one method: addResourceHandlers add resource handlers

Copy code 12345678910112131415161718192021222324 JAVA@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        // Default resource handling is disabled
        logger.debug("Default resource handling disabled");
        return;
    }
    // Cache control
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    // webjars configuration
    if (!registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
    // Static resource allocation
    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;

10.3 what is webjars?

The essence of Webjars is to introduce our static resources in the form of jar package. We used to import a static resource file directly.

Webjars is required to use SpringBoot. We can search:

Website: https://www.webjars.org

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

Copy code 12345 XML<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

After the import, view the webjars directory structure and visit jquery.com JS file!

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.4.1/jquery.js

10.4. The second static resource mapping rule

How can we import our own static resources in our project? Let's look at the next line of code;

We go to staticPathPattern and find the second mapping rule: / * *. When accessing any resources of the current project, it will find the class resourceProperties. We can click to see the analysis:

Copy code 12345678910111213 JAVA// Entry method
public String[] getStaticLocations() {
    return this.staticLocations;
}
// Find the corresponding value
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// Find path
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; This 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:

Copy code 1234 JAVA
#Static resource priority: Resources > static > public
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static(default)/"
"classpath:/public/"

We can create a new folder under the root directory of resources to store our static files;

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

10.5. Custom static resource path

We can also specify which folders we need to put static resource files through the configuration file. In application Configure in properties;

Copy code 1
PROPERTIESspring.resources.static-locations=classpath:/coding/,classpath:/kuang/

Once you define the path of the static folder, the original automatic configuration will become invalid!

Home page processing

After the static resource folder is finished, we continue to look down at the source code! You can see a map of the welcome page, which is our home page!

Copy code 12345678 JAVA@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService,ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // Getwelcome page to get the welcome page
        this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    return welcomePageHandlerMapping;
}

Click in and keep looking

Copy code 123456789101112 JAVAprivate Optional<Resource> getWelcomePage() {
    String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
    // : is a new operator introduced in java8
    // When Class::function, function belongs to Class and should be a static method.
    // The fund of this::function belongs to this object.
    // In short, it is just a kind of grammatical sugar, which is a kind of abbreviation
    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
// The welcome page is an index under location Just HTML
private Resource getIndexHtml(String location) {
    return this.resourceLoader.getResource(location + "index.html");
}

Welcome page, all indexes under the static resource folder HTML page; Mapped by / * * map.

Like my visit http://localhost:8080/ , you will find index. In the static resource folder html

Create a new index HTML, in any of the three directories above; Then access the test http://localhost:8080/ Look at the results!

Description of website Icon:

Like other static resources, Spring Boot looks for favicon in the configured static content location ico. If such a file exists, it will automatically be used as the favicon for the application.

1. Turn off the SpringBoot default icon

Copy code 1
PROPERTIES#Turn off the default icon spring mvc. favicon. enabled=false

2. Put an icon in the static resource directory, and I put it in the public directory

3. Clear browser cache! Refresh the web page and find that the icon has become your own!

Keywords: Java Front-end Spring Boot

Added by jesseledwards on Fri, 07 Jan 2022 22:35:49 +0200