SpringBoot之静态资源访问配置

  • Post author:
  • Post category:其他




一、默认静态资源映射规则


Spring Boot

默认将

/

的所有访问映射到以下目录:

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

接下来,在

main/resources

下新建

static



public



resources

三个文件夹,分别放入

a.png



b.png



c.png

三张图片,启动项目,分别访问:

http://localhost:8080/a.png
http://localhost:8080/b.png
http://localhost:8080/c.png

发现都能正常访问相应的图片资源。那么说明,

Spring Boot

默认会挨个从

public



resources



static

里面找是否存在相应的资源,如果有则直接返回。



二、配置访问自定义的资源访问路径



main/resources

目录下创建

mystatic

目录,目录下增加一个

1.png

图片资源文件,此时通过访问

http:localhost:8080/mystatic/1.png

返回的是

404 NOT FOUND

,有两种配置方式可以实现正常访问。

方式一:通过配置

application.yml

配置文件:

spring:
  mvc:
    static-path-pattern: /mystatic/**
  web:
    resources:
      static-locations: classpath:/mystatic/

方式二:通过继承

WebMvcConfigurer

并重写映射规则:

package com.study.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) {
        // 将/mystatic/**访问映射到classpath:/mystatic/
        registry.addResourceHandler("/mystatic/**").addResourceLocations("classpath:/mystatic/");
    }
}

以上两种配置方式等价,两种方法选择其一配置即可,如果同时配置,同时生效,可以大胆测试。

温馨提示:如果出现配置后无法正常访问时,将项目目录中的

target

目录删除后,重新编译启动,重试即可。



版权声明:本文为Pencil1312原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。