[关闭]
@hengbao 2018-06-04T07:20:22.000000Z 字数 1249 阅读 1375

Springboot配置静态资源url映射及对应的本地路径

SpringBoot


首先新建一个类,这个类属于适配器类型,放在配置相关的包下即可,或者放在拦截器过滤器一类的包下。

  1. package com.hahaha.intercept;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  7. @Configuration
  8. public class ResourcesConfigAdapter
  9. extends WebMvcConfigurerAdapter {
  10. @Value("${custom.server.download.dir}")
  11. private String resourceDir;
  12. @Override
  13. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  14. registry.addResourceHandler("/download/**").addResourceLocations("file:"+resourceDir);
  15. super.addResourceHandlers(registry);
  16. }
  17. }

我们只需要在addResourceHandler函数中传入需要匹配的路径,如上个例子中,我们写了/download/**,假设我们的服务器的地址为127.0.0.1端口为6666,那么我们在访问127.0.0.1:6666/download/1.txt或者127.0.0.1:6666/download/heiheihei/2.jpg(诸如此类)的时候,就会被这个适配器发现,然后对应资源路径寻找对应名称的文件。资源路径是使用addResourceLocations来进行配置的。这里,建议使用固定的路径,不用classpath一类,因为放在不同容器中可能路径会不同。这里还用到了@Value注解,这个注解的作用是加载配置文件中的属性。addResourceLocations函数中传入的值是"file:D:/helloworld/download/"当然了,对应到linux环境,你应该修改成这样的路径:file:/server/myapp/download。祝大家编程愉快,没有bug。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注