Springboot configures static resource url mapping and corresponding local path

First create a new class, this class belongs to the adapter type, and it can be placed under the configuration-related package, or under the package of the interceptor filter.

package com.hahaha.intercept;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class ResourcesConfigAdapter
        extends WebMvcConfigurerAdapter {

    @Value("${custom.server.download.dir}")
    private String resourceDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/download/**").addResourceLocations("file:"+resourceDir);
        super.addResourceHandlers(registry);
    }

}

We only need addResourceHandlerto pass in the path that needs to be matched in the function, as in the previous example, we wrote /download/**, assuming that the address of our server is the 127.0.0.1port 6666, then when we access 127.0.0.1:6666/download/1.txtor 127.0.0.1:6666/download/heiheihei/2.jpg(and so on), it will be discovered by this adapter, Then look for the file with the corresponding name corresponding to the resource path. Resource paths are addResourceLocationsconfigured using . Here, it is recommended to use a fixed path instead classpathof a class, because the paths may be different in different containers. Annotation is also used here @Value, and the function of this annotation is to load the properties in the configuration file. addResourceLocationsThe value passed in the function is of "file:D:/helloworld/download/"course, corresponding to the linux environment, you should modify it to this path: file:/server/myapp/download. Happy programming, no bugs.

Guess you like

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