SpringBoot开发案例之配置静态资源文件路径

简介:

89828

前言

SpringBoot本质上是为微服务而生的,以JAR的形式启动运行,但是有时候静态资源的访问是必不可少的,比如:image、js、css 等资源的访问。

默认静态资源路径

Spring Boot 对静态资源映射提供了默认配置,静态资源路径都是在classpath中:

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources

我们在src/main/resources目录下新建 public、resources、static 三个目录,并分别放入 1.jpg 2.jpg 3.jpg 三张图片。然后通过浏览器分别访问:

http://localhost:8080/1.jpg
http://localhost:8080/2.jpg
http://localhost:8080/3.jpg

地址均可以正常访问,Spring Boot 默认会从 public resources static 三个目录里面查找是否存在相应的资源。

新增静态资源路径

我们在spring.resources.static-locations后面追加一个配置classpath:/itstyle/:

# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默认的静态寻址资源目录 多个使用逗号分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/itstyle/

自定义静态资源映射

在实际开发中,我们可能需要自定义静态资源访问以及上传路径,特别是文件上传,不可能上传的运行的JAR服务中,那么可以通过继承WebMvcConfigurerAdapter来实现自定义路径映射。

application.properties 文件配置:

# 图片音频上传路径配置(win系统自行变更本地路径)
web.upload.path=/home/file/

WechatApplication.java 启动配置:

/**
 * 语音测评后台服务
 * 创建者 柒
 * 创建时间    2018年3月8日
 */
@SpringBootApplication
public class WechatApplication extends WebMvcConfigurerAdapter  {
    
    private final static Logger LOGGER = LoggerFactory.getLogger(WechatApplication.class);
    
    @Value("${web.upload.path}")
    private String uploadPath;
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/uploads/**").addResourceLocations(
                "file:"+uploadPath);
        LOGGER.info("自定义静态资源目录、此处功能用于文件映射");
    }
    
    public static void main(String[] args) {
        SpringApplication.run(WechatApplication.class);
        LOGGER.info("语音测评后台服务启动成功");
    }

}

我们可以访问以下路径:

http://localhost:8080/uploads/1.jpg

作者: 小柒

出处: https://blog.52itstyle.com

分享是快乐的,也见证了个人成长历程,文章大多都是工作经验总结以及平时学习积累,基于自身认知不足之处在所难免,也请大家指正,共同进步。

目录
相关文章
|
3月前
|
JavaScript 前端开发 Java
SpringBoot之静态资源规则与定制化
SpringBoot之静态资源规则与定制化
|
3月前
|
移动开发 Java HTML5
Springboot web静态资源配置
Springboot web静态资源配置
50 0
|
28天前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
23 0
|
2月前
day01_springboot综合案例(三)
day01_springboot综合案例
13 0
|
2月前
|
SQL
day01_springboot综合案例(二)
day01_springboot综合案例
48 0
|
2月前
|
SQL Java 数据库
day01_springboot综合案例(一)
day01_springboot综合案例
61 0
day01_springboot综合案例(一)
|
2月前
day02_springboot综合案例(三)
day02_springboot综合案例
25 0
|
2月前
day02_springboot综合案例(二)
day02_springboot综合案例
32 0
|
2月前
day02_springboot综合案例(一)
day02_springboot综合案例
41 0
|
3月前
|
Dubbo Java 应用服务中间件
Spring Boot + Dubbo + Zookpeer分布式案例
Spring Boot + Dubbo + Zookpeer分布式案例
36 0