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。

相关推荐
期待のcode33 分钟前
MyBatis-Plus的Wrapper核心体系
java·数据库·spring boot·后端·mybatis
老华带你飞1 小时前
出行旅游安排|基于springboot出行旅游安排系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring·旅游
m0_740043731 小时前
SpringBoot快速入门01- Spring 的 IOC/DI、AOP,
spring boot·后端·spring
JIngJaneIL1 小时前
基于Java饮食营养管理信息平台系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
老华带你飞2 小时前
垃圾分类|基于springboot 垃圾分类系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
古城小栈3 小时前
Spring Boot 集成区块链:智能合约调用接口开发全解析
spring boot·区块链·智能合约
kk哥88993 小时前
springboot静态资源的核心映射规则
java·spring boot·后端
Lyinj3 小时前
从一个编辑校验问题谈接口设计的边界
java·spring boot·python·学习
VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue非遗传承文化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Dwzun3 小时前
基于SpringBoot+Vue的农产品销售系统【附源码+文档+部署视频+讲解)
数据库·vue.js·spring boot·后端·毕业设计