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 that the springboot2 version cannot load static resources

2025-03-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces how to solve the problem that the springboot2 version can not load static resources. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Preface

In the process of learning springboot, it is found that static resources cannot be referenced. I am using the springboot2.2.1 version.

Trace the source code and finally solve it. And write down the solution.

Default load path

First of all, you need to know what the resource path that springboot loads by default is.

First of all, let's look at the class WebMvcAutoConfiguration. There is a method called addResourceHandlers ()

@ Configuration (proxyBeanMethods = false) @ ConditionalOnWebApplication (type = Type.SERVLET) @ ConditionalOnClass ({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class}) @ ConditionalOnMissingBean (WebMvcConfigurationSupport.class) @ AutoConfigureOrder (Ordered.HIGHEST_PRECEDENCE + 10) @ AutoConfigureAfter ({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class}) public class WebMvcAutoConfiguration {

@ 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 ()

/ / all / webjars/**, go to classpath:/META-INF/resources/webjars/ to find the resource if (! registry.hasMappingForPattern ("/ webjars/**")) {customizeResourceHandlerRegistration (registry.addResourceHandler ("/ webjars/**") .addResourceLocations ("classpath:/META-INF/resources/webjars/") .setCach ePeriod (getSeconds (cachePeriod)) .setCacheControl (cacheControl));}

/ / static resource folder mapping String staticPathPattern = this.mvcProperties.getStaticPathPattern ()

If (! registry.hasMappingForPattern (staticPathPattern)) {customizeResourceHandlerRegistration (registry.addResourceHandler (staticPathPattern) .addResourceLocations (getResourceLocations (this.resourceProperties.getStaticLocations () .setCachePeriod (getSeconds (cachePeriod)) .setCacheControl (cacheControl));}}

First, springboot will map the file under our classpath:/META-INF/resources/webjars/ path to / webjars/**

Then an if is used to determine the static resource folder mapping. First, determine whether we use "/ * *" for mapping.

If not, access "/ *" to any resources of the current project and go to (the folder of the following static resources) to find the mapping

"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" / ": the root path of the current project

What do you mean? To give an example, that is, by default, if we call http://localhost:8080/a.json

Springboot will look for the file a.json from these paths above.

The problem lies.

The source code is as guessed, so why can't I do mapping when accessing static resources directly in my code?

Let's take a closer look at the class WebMvcAutoConfiguration. There is a note on his head:

@ ConditionalOnMissingBean (WebMvcConfigurationSupport.class)

Shit suddenly realized it in an instant. In my profile:

@ Configurationpublic class MyMVCConfig extends WebMvcConfigurationSupport {...}

Inherit the class WebMvcConfigurationSupport, making the automatic assembly of springboot invalid. Because the purpose of the @ ConditionalOnMissingBean annotation is that when the class does not exist in the container, the following code works.

Why is it designed in this way?

Because sometimes our projects don't want springboot to automatically assemble for us. We hope it is entirely up to us to configure and control ourselves.

To achieve this effect, springboot provides us with a more concise way.

@ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.TYPE) @ Documented@Import (DelegatingWebMvcConfiguration.class) public @ interface EnableWebMvc {}

@ EnableWebMvc annotations are imported into DelegatingWebMvcConfiguration.clss

And DelegatingWebMvcConfiguration inherits WebMvcConfigurationSupport.

Public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

So when we add @ EnableWebMvc, it will have the same effect and simplicity.

Custom configuration resource mapping

Of course, springboot also supports us to specify the mapping path individually. I have summarized the following ways:

Configuration class

@ Configurationpublic class MyMVCConfig extends WebMvcConfigurationSupport {@ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ static/**") .addResourceLocations ("classpath:/static/");}}

Map all files under / static to / static/**

Configuration item

Add the following configuration items to the application.properties file

Spring.mvc.static-path-pattern=/**spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/,classpath:/public/

Spring.mvc.static-path-pattern=/**: indicates that all accesses go through static resource paths

Spring.resources.static-locations: configure the static resource path here.

On the springboot2 version can not load static resources how to solve the problem is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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