springboot static resource processing

Using springboot to develop web applications, you will encounter the problem of processing static resources (js, css, image, etc.). Based on springmvc development, we need to define in xml, such as:

<mvc:resources location="/static" mapping="/static/**"/>

In the above configuration, location defines the actual storage path of static files, and mapping defines the relative url of the browser to access static resources. If the local service is used, the corresponding image path is: http://localhost:8080/static /40836.jpg .

In springboot, the storage path of the file provides the corresponding default value corresponding to the location above:

  • The default static resource request path of Spring Boot is /**, for example: http://localhost:8080/40836.jpg .
  • The default resource storage path of SpringBoot is: classpath:/META-INF/resources,classpath:/resources,classpath:/static,classpath:/public/

    Custom static resource configuration

    Spring Boot provides two static resource configuration methods

  • Spring boot provides two parameters through application.properties
    to modify the actual storage path of static files and the relative url accessed by the browser. For the specific configuration, see the following
spring.mvc.static-path-pattern=/static/** #修改静态访问路径为:http://localhost:8080/static/40836.jpg.
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/statics/  #修改资源文件存放地址,如果多个用都好分割
  • Dynamic resource modification through java code configuration
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")//配置访问路径
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");//配置文件存放路径,如果多个,通过链式编程逐个添加
     }
}

If configuring through code, first define a Config class and use the @Configuration annotation. This class must implement WebMvcConfigureAdapter and override the addResourceHandlers method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324745447&siteId=291194637