SpringBoot自定义静态资源的映射

1. 通过配置类实现静态资源映射

在项目中的 src/main/resources目录下,创建文件夹backend,并在文件夹中创建HTML文件index.html和login.htm。
在这里插入图片描述
在config包下创建配置类WebMvcConfig,该配置类实现WebMvcConfigurer接口,并重写该接口的addResourceHandlers方法。

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 WebMvcConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        // 将 /backend/** 映射到 classpath:/backend/
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
    }
}

测试程序效果。启动项目,在浏览器中访问backend文件夹下的index.html。
在这里插入图片描述

2. 通过配置文件实现静态资源映射

application.yml配置

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

static-path-pattern:用于指定静态资源的访问路径
static-locations:用于指定静态资源存放目录

测试程序效果。启动项目,在浏览器中访问backend文件夹下的index.html。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_29385297/article/details/146123090
今日推荐