时间:2023-01-17 12:46:43 | 栏目:JAVA代码 | 点击:次
在看一个博客源码发现页面的图片所映射的地址在SpringBoot静态资源文件夹下找不到原來在这里是通过下面这段代码,将/store/**地址映射为getStorePath()得到的地址
registry.addResourceHandler("/store/**").addResourceLocations(getStorePath());
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/dist/**").addResourceLocations("classpath:/static/dist/"); registry.addResourceHandler("/theme/**").addResourceLocations("classpath:/static/theme/"); registry.addResourceHandler("/store/**").addResourceLocations(getStorePath()); super.addResourceHandlers(registry); }
实现 WebMvcConfigurer,重写addResourceHandlers(ResourceHandlerRegistry registry)方法
addResourceHandler()
:添加的是访问路径addResourceLocations()
:添加的是映射后的真实路径,映射的真实路径末尾必须加 / ,不然映射不到,这个问题困扰了我半天, / 适用于 windows和linux如下:
package cn.mindgd.config; import org.springframework.context.annotation.Bean; 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.WebMvcConfigurer; /** * 拦截器配置 */ @Configuration public class InterceptorConfig implements WebMvcConfigurer { /** * @author: JiaXinMa * @description: 访问静态文件 * @date: 2021/4/15 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //访问路径 registry.addResourceHandler("/api/upload/**") //映射真实路径 .addResourceLocations("file:" + System.getProperty("user.dir") + "/");//必须加"/",不然映射不到 } }
System.getProperty(“user.dir”) 是当前项目路径