SpringBoot配置静态资源映射的两种方式

SpringBoot配置静态资源映射有两种方式

  1. 使用配置文件
spring:
  web:
    resources:
    # 开启静态资源映射
      add-mappings: true
    # 设置静态资源位置,可以设置多个
      static-locations: classpath:a/, classpath:/b/

访问路径 localhost:8080/hello.html

SpringBoot会自动去类路径下的a文件夹和b文件夹下寻找hello.html,请求路径不用带上文件夹名称

  1. 使用配置类

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    
    // 设置静态资源映射
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }
}

访问路径localhost:8080/**/backend/hello.html
SpringBoot会去类路径下的backend文件夹下寻找hello.html

访问路径localhost:8080/**/front/hello.html
SpringBoot会去类路径下的front文件夹下寻找hello.html

总结

使用配置文件方式,只需要文件匹配
使用配置类方式,需要路径匹配以及文件匹配

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,静态资源映射是由Spring Boot默认提供的配置完成的。Spring Boot将所有访问映射到以下目录:classpath:/static、classpath:/public、classpath:/resources和classpath:/META-INF/resources。如果这些目录中有多张同名的图片,访问地址的优先级顺序为:META-INF/resources > resources > static > public。\[2\] 如果我们请求一个以".html"结尾的静态资源Spring Boot会按照优先级高的文件夹先查找,然后再查找优先级低的文件夹,直到找到指定的静态资源为止。\[3\] 例如,在src/main/resources/static目录下创建了一个hello.html文件,当我们启动Spring Boot并访问"http://localhost:8080/hello.html"时,就会显示该hello.html页面。\[3\] 总结来说,Spring Boot静态资源映射提供了默认配置,可以直接将静态资源放置在指定的目录中,无需进行额外的配置即可访问这些静态资源。\[1\] #### 引用[.reference_title] - *1* *3* [Spring Boot静态资源映射](https://blog.csdn.net/weixin_64842782/article/details/125089662)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot静态资源映射](https://blog.csdn.net/ChOLg/article/details/102800978)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值