Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of SpringBoot static resource import and home page setting

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to solve the problem of SpringBoot static resource import and home page setting, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

1. Static resource import

In the Web development process, we need to come into contact with many static resources, such as CSS, JS, pictures, etc. In the previous development process, these resources are placed in the Web directory and can be accessed according to the corresponding path when needed. However, in the SpringBoot project, there is no Web directory, so where to put these static resources, and how to access it?

Since it is the configuration in the Web application, if you look at the corresponding autoconfiguration class WebMvcAutoConfiguration, you can see the method addResourceHandlers that handles resources.

@ Overridepublic void addResourceHandlers (ResourceHandlerRegistry registry) {if (! this.resourceProperties.isAddMappings ()) {logger.debug ("Default resource handling disabled"); return;} addResourceHandler (registry, "/ webjars/**", "classpath:/META-INF/resources/webjars/"); 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);});}

Among them, the role of this.resourceProperties.isAddMappings () is to determine whether the access path to the resource is specified in the configuration file. If so, this method does not take effect and returns directly; if not, continue to execute the method and go to the default location to find the resource.

1.1 WebJars

WebJars is the Jar package form of front-end resources, which allows us to use front-end frameworks and components in the form of Jar packages.

WebJars website: https://www.webjars.org/.

Why use WebJars?

When developing Java web projects, we will use build tools such as Maven,Gradle to achieve version dependency management of jar packages, as well as automatic project management, but for front-end resource packages such as JS,Css, we can only copy them to the webapp directory manually, which will not be able to manage these resources dependently, and can easily lead to file confusion, version inconsistencies and other problems. WebJars provides us with the jar package form of these front-end resources, and we can manage dependencies.

If we want to use JQuery, according to the previous practice, we have to download the JS file of JQuery from the Internet and put it under statics/js in the web directory (that's what we did when we used AJAX); but now we can use WebJars.

First find the Maven coordinates of JQuery in the WebJars website and put it in the pom file of the project

Org.webjars jquery 3.6.0

After introduction, you can see org.webjars:jquery:3.6.0 in the External Libaries of the project!

So how do we access it? In fact, the path is already given in the above source code.

AddResourceHandler (registry, "/ webjars/**", "classpath:/META-INF/resources/webjars/")

This line of code maps all access under / webjars/ to classpath:/META-INF/resources/webjars/, that is, we only need to find the / jquery/3.6.0/jquery.js file under the classpath through / webjars/!

Run the project and type http://localhost:8080/webjars/jquery/3.6.0/jquery.js in the browser, which does show the jquery.js file!

Files introduced in WebJars are in line with the structure in the above figure, that is, they can be accessed through the classpath:/META-INF/resources/webjars/ path, so that the settings in the code are associated with external files!

1.2 staticPathPattern

Going back to the source code, there is the last of the three sentences of this method (long but indeed one).

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

This is a bit complicated (the previous version of the source code is a little easier to understand), but you can see the getStaticPathPattern () method to get the static path, click into it.

Public String getStaticPathPattern () {return this.staticPathPattern;}

This method returns staticPathPattern directly. Continue.

/ * Path pattern used for static resources. * / private String staticPathPattern = "/ *"

At this point, you will see that it is actually the default static resource path! This path can also be set through spring.mvc. If it is not set, it is all the paths under the project / *!

Then in the Web attribute class WebProperties, there is a resource class Resource, which also sets four paths (jump a little too big, let's see it first), among which

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

Classpath:/META-INF/resources/ is the WebJars path above

Classpath:/resources/ is the resources/resources/ path

Classpath:/static/ is the resources/static/ path

Classpath:/public/ is the resources/public path

That is, all access requests through / * (without configuration) will look for static resources in these four paths!

There is only one directory static in the default resource. Here, create all the above directories and put them into a js file for testing.

Run the project at this time, visit http://localhost:8080/public.js, http://localhost:8080/resources.js, http://localhost:8080/static.js, you can display the corresponding js file content!

Note: if the files in the three directories have duplicate names, the priority is the order of the CLASSPATH_RESOURCE_LOCATIONS array, which can be understood as not looking for the latter if you find it in the previous path!

two。 Home page settings

As above, find the corresponding source code first

Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping (ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping (new TemplateAvailabilityProviders (applicationContext), applicationContext, getWelcomePage (), this.mvcProperties.getStaticPathPattern ()); welcomePageHandlerMapping.setInterceptors (getInterceptors (mvcConversionService, mvcResourceUrlProvider)); welcomePageHandlerMapping.setCorsConfigurations (getCorsConfigurations ()); return welcomePageHandlerMapping;}

It's long and complicated, but you just need to pay attention to the getWelcomePage () method and click in to have a look.

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

These three methods are called layer by layer (although I don't know why), but you know that location is the above three directories resources, static, and public, and the default home page is index.html. In other words, if the index.html file exists in these three directories, then it is the default home page! The demonstration is omitted, which is not a difficult point anyway!

The answer to the question about how to solve the problem of SpringBoot static resource import and home page setting is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report