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。

相关推荐
jiankeljx2 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
Mr.45672 小时前
JDK17+Druid+SpringBoot3+ShardingSphere5 多表分库分表完整实践(MySQL+PostgreSQL)【生产优化版】
数据库·spring boot·后端
逸Y 仙X2 小时前
文章十二:索引数据的写入和删除
java·大数据·spring boot·spring·elasticsearch·搜索引擎·全文检索
yashuk2 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
strayCat232552 小时前
4. Spring Boot 数据持久化(JPA)
java·spring boot·后端
strayCat232552 小时前
2. Spring Boot 自动配置原理深度解析
java·spring boot·后端
武超杰2 小时前
SpringBoot 进阶实战:异常处理、单元测试、多环境、日志配置全解析
spring boot·单元测试·log4j
polaris06303 小时前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
tumeng07113 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
码视野3 小时前
#Cursor加Specs编程,3小时上线一个有管理后台和移动端的检举举报全流程平台(完全开源)
spring boot·小程序·ai编程