sprintboot动态静态资源转发

背景|

    要做一个功能,根据规则服务器上创建文件后,返回可下载的链接
     
    因为sprintboot中地址需要先在用@RequestMapping定义好,否则解析不了,这时动态生成的文件下载地址就会报错。
 

 解决方法|

    添加一个资源的处理器,将某一个路径地址映射到服务器的某一路径下
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 StaticConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/channels/**").addResourceLocations("file:/opt/channel/");
        super.addResourceHandlers(registry);
    }
}
/channels/**:**是通配符,路径在/channels/下就会命中
/opt/channel/:指代本地映射的路径,路径前要加file:
 

注意:

    addResourceLocations的目录,最后必须以/结尾,否则不生效

猜你喜欢

转载自www.cnblogs.com/meitian/p/11396651.html