SpringBoot之静态资源加载顺序及磁盘目录资源访问设置

SpringBoot静态资源加载顺序

文章目录

  • SpringBoot静态资源加载顺序
  • 1.静态资源访问
    • 1.静态资源目录
    • 2.静态资源访问前缀
    • 3. 改变默认的静态资源路径
    • 4. webjars
  • 2. 访问外部资源(如磁盘目录)
    • 1. 只有配置类
    • 2. application.yml+配置类

1.静态资源访问

原理: 静态映射/**

请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

1.静态资源目录

只要静态资源放在类路径下: /static(or/publicor/resourcesor/META-INF/resources`

# 优先级由高到低依次排列如下:
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public

访问 : 当前项目根路径/ + 静态资源名 ,如:http://localhost:8080/my.png

2.静态资源访问前缀

默认无前缀,这里指定前缀为res,配置如下

spring:
  mvc:
    static-path-pattern: /res/**
    # 注意:配置了前缀,会导致 Favicon 功能失效

访问:当前项目根路径/+访问前缀+静态资源名,如:http://localhost:8080/res/my.png

3. 改变默认的静态资源路径

spring:
  mvc:
    static-path-pattern: /res/** 
# 设置静态资源文件夹
  resources:
    static-locations: [classpath:/test/]

访问: 当前项目根路径/ + 静态资源文件夹/+ 静态资源名,如:http://localhost:8080/res/test/my.png

4. webjars

自动映射 /webjars/**

  1. 如引入vue3.js
<dependency>
   <groupId>org.webjars.npmgroupId>
   <artifactId>vueartifactId>
   <version>3.2.41version>
dependency>

访问地址:http://localhost:8080/webjars/vue/3.2.41/dist/vue.global.js

  1. 可以不显示版本号,需要引入下面依赖

<dependency>
   <groupId>org.webjarsgroupId>
   <artifactId>webjars-locatorartifactId>
   <version>0.45version>
dependency>
<dependency>
   <groupId>org.webjars.npmgroupId>
   <artifactId>vueartifactId>
   <version>3.2.41version>
dependency>

访问地址:http://localhost:8080/webjars/vue/dist/vue.global.js

2. 访问外部资源(如磁盘目录)

目的:spring boot 访问 windows系统 磁盘目录中的资源

注意:

  1. 此配置与classpath:/META-INF/resourcesclasspath:/resourcesclasspath:/staticclasspath:/public不冲突,都能正常访问

  2. 访问.xls、.xlsx、.doc、.docx、.md 结尾的文件时会直接下载

  3. 访问 .png、.jpg、.pdf、.html,.js 结尾的文件时会在浏览器直接打开

将磁盘D:\aa\files\目录与E:\000\myDiskFiles\下的所有文件通过Spring boot映射后访问,文件目录及文件位置如下:

D:\aa\files\images\logo.png
D:\aa\files\pdf\test.pdf

E:\000\myDiskFiles\excel\demo.xlsx
E:\000\myDiskFiles\html\demo.html
E:\000\myDiskFiles\images\demo.png
E:\000\myDiskFiles\js\demo.js
E:\000\myDiskFiles\markdown\demo.md
E:\000\myDiskFiles\word\demo.docx

http://localhost:8080/diskPath/images/logo.png

http://localhost:8080/diskPath/pdf/test.pdf
http://localhost:8080/diskPath/excel/demo.xlsx
http://localhost:8080/diskPath/html/demo.html
http://localhost:8080/diskPath/images/demo.png
http://localhost:8080/diskPath/js/demo.js
http://localhost:8080/diskPath/markdown/demo.md
http://localhost:8080/diskPath/word/demo.docx

1. 只有配置类

  1. 映射到同一个前缀/diskPath/**开头的路径下,配置类MyWebMvcConfig.java如下,
package com.yuan.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
   @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //写法一:
        //注意files:前缀不能丢,
        registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/D:/aa/files/");
        registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/E:/000/myDiskFiles/");
        //去掉file:后的/ 也是可以的
        //registry.addResourceHandler("/diskPath/**").addResourceLocations("file:D:/aa/files/");
        //registry.addResourceHandler("/diskPath/**").addResourceLocations("file:E:/000/myDiskFiles/");

        // 写法二:
        //registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/D:/aa/files/").addResourceLocations("file:/E:/000/myDiskFiles/");
        // 写法三:
        /***
         * 1. 可以通过前缀 diskPath 或 test都可访问到对应磁盘的资源,
         * 让问地址:
         * http://localhost:8080/项目根目录/diskPath/pdf/test.pdf
         * http://localhost:8080/项目根目录/test/html/demo.html
         */
        registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/D:/aa/files/").addResourceLocations("file:/E:/000/myDiskFiles/");
        registry.addResourceHandler("/test/**").addResourceLocations("file:/D:/aa/files/").addResourceLocations("file:/E:/000/myDiskFiles/");
    }

    /***
     * http://localhost:8080/diskPath/images/logo.png
     *
     * http://localhost:8080/diskPath/pdf/test.pdf
     *
     * http://localhost:8080/diskPath/excel/demo.xlsx
     *
     * http://localhost:8080/diskPath/html/demo.html
     *
     * http://localhost:8080/diskPath/images/demo.png
     *
     * http://localhost:8080/diskPath/js/demo.js
     *
     * http://localhost:8080/diskPath/markdown/demo.md
     *
     * http://localhost:8080/diskPath/word/demo.docx
     */
}

//错误写法:
//registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/D:/aa/files/,file:/E:/000/myDiskFiles/");
//registry.addResourceHandler("/diskPath/**").addResourceLocations("file:/D:/aa/files/,/E:/000/myDiskFiles/");

2. application.yml+配置类

  1. application.yml
spring:
  application:
    name: yuan-boot-static
yuan:
  d_diskPath: file:D:/aa/files/images/
  e_diskPath: file:E:/000/myDiskFiles/
  1. 映射到同一个前缀/diskPath/**开头的路径下,配置类MyWebMvcConfig.java如下
package com.yuan.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Value("${yuan.d_diskPath}")
    private String d_diskFilePath;
    @Value("${yuan.e_diskPath}")
    private String e_diskFilePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("D:盘映射路径===" + d_diskFilePath);
        System.out.println("E:盘映射路径===" + e_diskFilePath);
        registry.addResourceHandler("/diskPath/**").addResourceLocations(d_diskFilePath).addResourceLocations(e_diskFilePath);
    }
}

  1. 启动控制台打印如下:
....

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.5)

2022-11-04 14:12:57.189  INFO 13692 --- [  restartedMain] com.yuan.YuanBootDiskfileApplication     : Starting YuanBootDiskfileApplication using Java 1.8.0_191 on jinshengyuan with PID 13692 (G:\MyGitProject\yuan-boot-integrate\yuan-boot-static\yuan-boot-diskfile\target\classes started by yuanjinsheng in G:\MyGitProject\yuan-boot-integrate)
2022-11-04 14:12:57.191  INFO 13692 --- [  restartedMain] com.yuan.YuanBootDiskfileApplication     : No active profile set, falling back to 1 default profile: "default"
2022-11-04 14:12:57.239  INFO 13692 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-11-04 14:12:57.239  INFO 13692 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-11-04 14:12:58.033  INFO 13692 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-11-04 14:12:58.044  INFO 13692 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-11-04 14:12:58.044  INFO 13692 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-11-04 14:12:58.122  INFO 13692 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-11-04 14:12:58.122  INFO 13692 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 882 ms
D:盘映射路径===file:D:/aa/files/images/
E:盘映射路径===file:E:/000/myDiskFiles/
2022-11-04 14:12:58.353  WARN 13692 --- [  restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates, check your Thymeleaf configuration, or set spring.thymeleaf.check-template-location=false)
2022-11-04 14:12:58.394  INFO 13692 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-11-04 14:12:58.416  INFO 13692 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-11-04 14:12:58.423  INFO 13692 --- [  restartedMain] com.yuan.YuanBootDiskfileApplication     : Started YuanBootDiskfileApplication in 1.673 seconds (JVM running for 2.592)

访问地址:

http://localhost:8080/diskPath/pdf/test.pdf
http://localhost:8080/diskPath/excel/demo.xlsx
http://localhost:8080/diskPath/html/demo.html
http://localhost:8080/diskPath/images/demo.png
http://localhost:8080/diskPath/js/demo.js
http://localhost:8080/diskPath/markdown/demo.md
:8080/diskPath/pdf/test.pdf
http://localhost:8080/diskPath/excel/demo.xlsx
http://localhost:8080/diskPath/html/demo.html
http://localhost:8080/diskPath/images/demo.png
http://localhost:8080/diskPath/js/demo.js
http://localhost:8080/diskPath/markdown/demo.md
http://localhost:8080/diskPath/word/demo.docx

你可能感兴趣的:(Springboot,spring,boot,后端,java)