【SpringBoot】自定义策略的静态资源访问

文章介绍了在SpringBoot项目中处理静态资源,如图片的两种方法。一种是通过实现WebMvcConfigurer接口并重写addResourceHandlers方法,另一种是在application.properties中直接配置。两种方式均示例了如何访问静态文件,并提供了具体的路径配置。

新建static文件夹,存储图片等资源

在这里插入图片描述
项目版本信息:SpringBoot版本为2.3.3.RELEASE,JDK1.8

方式一 Java编码定义

配置类实现WebMvcConfigurer接口,然后实现该接口的addResourceHandlers方法。

  • 关键代码:registry.addResourceHandler(“/static/**”).addResourceLocations(“classpath:/static/”);
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    
    @Value("${photo.dir}")
    private String realPath;
    /**
     * 添加静态资源访问
     *
     * @param registry 类位置:
     * @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 示例1
        registry.addResourceHandler("/static/**").          
                addResourceLocations("classpath:/static/");
         // 示例2       
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:"+realPath);

    }
}

application.properties中定义realPath即图片存储的实际位置。

# 端口号
server.port=8081
# 设置context-path
server.servlet.context-path=/studyboot2023
# 静态资源存放位置路径(以/结尾)
photo.dir=/Users/wzp/IdeaProjects/SpringBootReview202305/study01/src/main/resources/static/photo/

重启项目,在浏览器中输入
http://localhost:8081/studyboot2023/static/photo/xidianlogonew.png

http://localhost:8081/studyboot2023/upload/xidianlogonew.png
即可看到classpath:/static/下存放的图片资源。

方式二 配置中定义

无需配置类,直接在application.properties中定义

spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

过滤规则为/static/**,静态资源位置为classpath:/static
重启项目后访问:http://localhost:8081/studyboot2023/static/photo/xidianlogonew.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值