wszyyo 2022-12-30 23:45 采纳率: 30%
浏览 228

springBoot静态资源路径映射配置不生效,浏览器访问为404

springBoot静态资源路径映射配置不生效,浏览器访问为404

因为Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。
所以在配置文件中也配置了spring.mvc.pathmatch.matching-strategy=ant-path-matcher,但还是没有任何效果


@Slf4j
@Configuration
public class templateWebMvcConfig implements WebMvcConfigurer{
        private static String localhostPath = "file:/Users/zhuyuanyang/Desktop/test/javaimg/";
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            log.info("开始解析地址");
            registry.addResourceHandler("/images/**").
                    addResourceLocations(localhostPath);
            log.info("结束解析地址");


        }
}
  • 写回答

2条回答 默认 最新

  • ShowMeAI 2022-12-31 00:15
    关注

    Spring Boot 中,使用 addResourceLocations() 方法配置资源映射路径时,应将本地路径写成 "file:/" 形式的绝对路径。例如:

    registry.addResourceHandler("/images/**").
      addResourceLocations("file:/Users/zhuyuanyang/Desktop/test/javaimg/");
    

    另外,如果您希望将项目打包成 jar 包之后,资源文件仍然能够被正常访问,可以使用 classpath 协议,将本地路径写成 "classpath:/" 形式的相对路径。例如:

    registry.addResourceHandler("/images/**").
      addResourceLocations("classpath:/static/images/");
    

    这样,在项目打包成 jar 包之后,资源文件仍然能够被正常访问。

    评论

报告相同问题?

问题事件

  • 创建了问题 12月30日