SpringBoot web静态资源映射

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot web静态资源映射

流楚丶格念   2022-09-29 我要评论

静态资源映射规则

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

静态资源的文件夹包括:

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

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

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

这里就放着static下了,

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

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

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

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

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

在static下创建index.html

编写网页代码:

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

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

如果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="../test1.jpg">
</body>
</html>

再进行访问如下:

自定义静态资源映射规则

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

代码如下:

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盘的图片也是可以的:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们