SpringBoot自定义静态资源的映射

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

在项目中的 src/main/resources目录下,创建文件夹backend,并在文件夹中创建HTML文件index.html和login.htm。

在config包下创建配置类WebMvcConfig,该配置类实现WebMvcConfigurer接口,并重写该接口的addResourceHandlers方法。

java 复制代码
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配置

yaml 复制代码
spring:
  mvc:
    static-path-pattern: /backend/**
  web:
    resources:
      static-locations: classpath:/backend/

static-path-pattern:用于指定静态资源的访问路径

static-locations:用于指定静态资源存放目录

测试程序效果。启动项目,在浏览器中访问backend文件夹下的index.html。

相关推荐
后端小张15 小时前
基于飞算AI的图书管理系统设计与实现
spring boot
考虑考虑1 天前
Jpa使用union all
java·spring boot·后端
阿杆2 天前
同事嫌参数校验太丑,我直接掏出了更优雅的 SpEL Validator
java·spring boot·后端
昵称为空C2 天前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
麦兜*3 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
麦兜*3 天前
MongoDB 在物联网(IoT)中的应用:海量时序数据处理方案
java·数据库·spring boot·物联网·mongodb·spring
汤姆yu3 天前
基于springboot的毕业旅游一站式定制系统
spring boot·后端·旅游
计算机毕业设计木哥3 天前
计算机毕设选题推荐:基于Java+SpringBoot物品租赁管理系统【源码+文档+调试】
java·vue.js·spring boot·mysql·spark·毕业设计·课程设计
hdsoft_huge3 天前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
AD钙奶-lalala3 天前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket