Springboot配置内置Tomcat的虚拟路径映射

Springboot配置内置Tomcat的虚拟路径映射

由于Springboot使用的是内置的tomcat,因此我们需要创建如下一个配置类,继承WebMvcConfigurer,重写其方法

addResourceHandler() : 指访问路径,相当于Setting.xml里的path属性

addResourceLocations() :前面要有"file:" 后面接上映射的路径,相当于Setting.xml里面的docBase属性

网上有一些是继承 WebMvcConfigurerAdapter 这个已经过时了。官方建议WebMvcConfigurer

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pic/**").addResourceLocations("file:D:/picture/");
    }
}

访问路径应该是 【ip】:【端口】/【配置文件的context-path】/itemPic/【图片名称】

例如

在d:/picture/里放了一张叫test.png图片

Springboot配置内置Tomcat的虚拟路径映射_第1张图片
假设 ip 为 localhost 端口为 8080 applaction配置文件配置的 server.servlet.context-path: /demo 虚拟路径如上文配置。
在这里插入图片描述
访问路径应该为 localhost:8080/demo/pic/test.png

这个是支持子文件夹的,如果test.png 在 D:/picture/2021/06/19/test.png

访问路径就应该为 localhost:8080/demo/pic/2021/06/19/test.png

相当于 localhost:8080/demo/pic/ 取代了 D:/picture /

你可能感兴趣的:(tomcat,spring,boot)