服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot重写addResourceHandlers映射文件路径方式

SpringBoot重写addResourceHandlers映射文件路径方式

2022-07-21 10:04维1 Java教程

这篇文章主要介绍了SpringBoot重写addResourceHandlers映射文件路径方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

重写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”) 是当前项目路径

SpringBoot重写addResourceHandlers映射文件路径方式

成功访问如下

SpringBoot重写addResourceHandlers映射文件路径方式

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_37859539/article/details/82912851

延伸 · 阅读

精彩推荐