Web development static resource processing

7. Web development static resource processing

7.1 static resource processing

We need to introduce front-end resources. There are many static resources in the project, such as css, js and other files. How is this SpringBoot handled?

If we are a web application, there will be a webapp under our main. We used to import all the pages here! But our current pom is packaged in 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,

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

There is one method: addResourceHandlers add resource handlers

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        // Default resource handling is disabled
        logger.debug("Default resource handling disabled");
        return;
    }
    // webjars configuration
    addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
    // Static resource allocation
    addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
        registration.addResourceLocations(this.resourceProperties.getStaticLocations());
        if (this.servletContext != null) {
            ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
            registration.addResourceLocations(resource);
        }
    });
}

Read the source code, such as all / webjars / * *, and you need to find the corresponding resources in classpath:/META-INF/resources/webjars /

7.2 webjars static resources

The essence of Webjars is to introduce 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 the website: https://www.webjars.org

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

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

After importing, check the webjars directory structure in External Libraries and access the Jquery.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.6.0/jquery.js

7.3 import your own static resources

How to import static resources if you use them in your 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 look for the class resourceProperties, which inherits the static internal class Resources in the WebProperties class. We can click to see the analysis:

resourceProperties class

//getStaticLocations() in the resourceProperties class calling the parent class.
@Override
@DeprecatedConfigurationProperty(replacement = "spring.web.resources.static-locations")
public String[] getStaticLocations() {
    return super.getStaticLocations();
}

Click getStaticLocations() to enter the static internal class Resources of the WebProperties class

public static class Resources {

		private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
				"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

		/**
		 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
		 * /resources/, /static/, /public/].
		 */
		private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

		public String[] getStaticLocations() {
			return this.staticLocations;
		}
    // ...
}

In the Resources class, you can set parameters related to static Resources, which point to the folder to find Resources, that is, the path of the above array,

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

"classpath:/META-INF/resources/"
"classpath:/resources/"  // 1
"classpath:/static/"     // 2
"classpath:/public/"     // 3

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

Create a new folder static under the root directory of resources, and create a test.js file in the static directory to access http://localhost:8080/test.js , it will look for the corresponding static resource files in these folders

7.4 custom static resource path

We can also specify the storage path of the static resource file in the configuration file application.properties. Once we define the path of the static folder, the original automatic configuration will become invalid!

spring.resources.static-locations=classpath:/aadzj/,classpath:/dengzj/

7.5 home page processing

After finishing the static resource folder, we continue to look down at the source code in the webmvcoautoconfiguration configuration configuration class! You can see a map 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(),// Getwelcome page to get the welcome page
            this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
    return welcomePageHandlerMapping;
}

Click getwelcome page () to continue

private Resource getWelcomePage() {
    for (String location : this.resourceProperties.getStaticLocations()) {
        Resource indexHtml = getIndexHtml(location);
        if (indexHtml != null) {
            return indexHtml;
        }
    }
    ServletContext servletContext = getServletContext();
    if (servletContext != null) {
        return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
    }
    return null;
}

private Resource getIndexHtml(String location) {
    return getIndexHtml(this.resourceLoader.getResource(location));
}

private Resource getIndexHtml(Resource location) {
    try {
        Resource resource = location.createRelative("index.html");
        if (resource.exists() && (resource.getURL() != null)) {
            return resource;
        }
    }
    catch (Exception ex) {
    }
    return null;
}

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

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

7.6 website Icon

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

1. Turn off the SpringBoot default icon

#Turn off the default icon, and the higher version of SpringBoot has expired
spring.mvc.favicon.enabled=false

2. Put an icon in the static resource directory and name it favicon.ico, for example, in the public directory

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

Keywords: Spring Boot

Added by vinnier on Tue, 07 Dec 2021 21:12:42 +0200