Springboot笔记<5>静态资源访问

 


静态资源访问

静态资源目录

请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面。如果静态目录中存在a.png,访问localhost:8080/a.png也不会访问到a.png,而是会得到字符串"student"。因为请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。

@Slf4j
@RestController
public class StudentController {
    @RequestMapping("/a.png")
    public String handle02() {
        return "student";
    }

}

WebMvcAutoConfiguration类自动为我们注册了如下目录为静态资源目录(favicon.ico,html等),也就是说直接可访问到资源的目录。优先级从高到低分别是:

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/
  5. /当前项目的根路径(resources)

WebMvcAutoConfiguration注册的对应的主页:

  1. classpath:/META-INF/resources/index.html
  2. classpath:/resources/index.html
  3. classpath:/static/index.html
  4. classpath:/public/index.html
  5. /index.html

从上到下。所以,如果static里面有个index.html,public下面也有个index.html,则优先会加载static下面的index.html。

静态资源访问前缀

spring:
  mvc:
    static-path-pattern: /res/**
  web:
    resources:
      static-locations: [classpath:/haha/]

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找

例如原先访问地址为{http://localhost:9999/a.png},加上前缀之后的访问地址是『http://localhost:9999/res/a.png』,静态资源处理器会去『 classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ **classpath:/public/****/:当前项目的根路径』下去寻找index.html。如果配置了static-locations: classpath:/haha,则静态文件会去/haha下找。

自动映射 webjars

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径 <artifactId>,<version>。

welcomePage

  • 静态资源路径下 index.html

    • 可以配置静态资源路径
    • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
  • 配置1依然可以通过ip+port访问welcomePage

  • 配置2不能可以通过ip+port访问welcomePage,只能ip+port/index.html

#配置1
spring:
  web:
    resources:
      static-locations: [classpath:/haha/]
#配置2
spring:
  mvc:
    static-path-pattern: /res/**
  web:
    resources:
      static-locations: [classpath:/haha/]

favicon.ico

favicon.ico 放在静态资源目录下即可,增加访问前缀会使图标失效

静态资源配置原理

  • SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
  • SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效

SpringBoot启动会默认加载很多xxxAutoConfiguration类(自动配置类),其中SpringMVC的大都数功能都集中在WebMvcAutoConfiguration类中,根据条件ConditionalOnxxx注册类对象;WebMvcAutoConfiguration满足以下ConditionalOnxxx条件,类是生效的,并把其对象注册到容器中。

posted @   aixueforever  阅读(137)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示