• 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条件,类是生效的,并把其对象注册到容器中。

    未经作者同意请勿转载

    本文来自博客园作者:aixueforever,原文链接:https://www.cnblogs.com/aslanvon/p/15715163.html

  • 相关阅读:
    设计模式之策略模式
    UML类图几种关系的总结
    LinuxMint下安装使用Umbrello(UML工具)
    Linux环境变量
    随笔
    Unity Animation Scripting zz
    FSM:游戏开发中的有限状态机(理论篇)转
    统计帧率的几种方法
    图形学 游戏 学习链接汇总
    福尔摩斯女友
  • 原文地址:https://www.cnblogs.com/aslanvon/p/15715163.html
Copyright © 2020-2023  润新知