目录
  • 静态资源映射规则
  • 自定义静态资源映射规则

静态资源映射规则

“/**” 访问当前项目任何资源,全部找静态资源的文件夹进行映射

静态资源的文件夹包括:

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/"

静态资源路径下的文件,可以通过地址栏直接访问。

例如:我们在在static,public,resources或者META-INF/resources/下放图片test1.jpg

SpringBoot web静态资源映射实现步骤详解

这里就放着static下了,

SpringBoot web静态资源映射实现步骤详解

然后我们在application.properties中配置静态资源位置:

PS:低版本的Springboot好像是真的不用配置就能访问,但是高版本不行了,看了很多帖子,是说的要配置一下

spring.web.resources.static-locations=classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources

SpringBoot web静态资源映射实现步骤详解

我们启动服务器,就可以直接在地址栏中访问:

SpringBoot web静态资源映射实现步骤详解

“/**” 访问静态资源文件夹下的所有index.html页面

在static下创建index.html

SpringBoot web静态资源映射实现步骤详解

编写网页代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>
        莫名其妙的首页!
    </h1>
    <img src="https://www.freexyz.cn/dev/test1.jpg">
</body>
</html>

通过地址栏直接访问index.html

SpringBoot web静态资源映射实现步骤详解

如果index.html的位置在/static/lala/index.html,则相应的访问路径也要为/lala/index.html

Img标签的src属性为”…/timg.jpg”

index.html修改后如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>
        莫名其妙的首页!
    </h1>
    <img src="https://www.freexyz.cn/test1.jpg">
</body>
</html>

再进行访问如下:

SpringBoot web静态资源映射实现步骤详解

自定义静态资源映射规则

我们需要建立自定义配置类,配置类实现WebMvcConfigurer中的addResourceHandlers方法,即可进行自定义资源映射路径的添加

SpringBoot web静态资源映射实现步骤详解

代码如下:

package com.yyl.firstdemo.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 MyWebAppConfigurer implements WebMvcConfigurer {
    // 添加自定义资源映射路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //addResourceHandler 添加资源处理url路径
        //addResourceLocations 添加url对应的磁盘物理路径
        registry.addResourceHandler("/**").
                addResourceLocations("classpath:/META-INF/resources/",
                        "classpath:/resources/",
                        "classpath:/static/",
                        "classpath:/public/",
                        "file:D:/Study/图片/图片/");
    }
}

再访问D盘的图片也是可以的:

SpringBoot web静态资源映射实现步骤详解

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。