重写addResourceHandlers映射文件路径
在看一个博客源码发现页面的图片所映射的地址在SpringBoot静态资源文件夹下找不到原來在这里是通过下面这段代码,将/store/**地址映射为getStorePath()得到的地址
在此记录以下
1
|
registry.addResourceHandler( "/store/**" ).addResourceLocations(getStorePath()); |
1
2
3
4
5
6
7
|
@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); } |
配置本地资源映射路径 addResourceHandlers
实现 WebMvcConfigurer,重写addResourceHandlers(ResourceHandlerRegistry registry)方法
-
addResourceHandler()
:添加的是访问路径 -
addResourceLocations()
:添加的是映射后的真实路径,映射的真实路径末尾必须加 / ,不然映射不到,这个问题困扰了我半天, / 适用于 windows和linux
如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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”) 是当前项目路径
成功访问如下
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_37859539/article/details/82912851