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 addResourceHandler
to 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.1
port 6666
, then when we access 127.0.0.1:6666/download/1.txt
or 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 addResourceLocations
configured using . Here, it is recommended to use a fixed path instead classpath
of 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. addResourceLocations
The 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.