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。

相关推荐
梓沂8 分钟前
dockercompose启动mysql容器和springboot项目容器时,mysql容器启动慢导致springboot项目容器启动失败
数据库·spring boot·mysql
愿你天黑有灯下雨有伞10 分钟前
Spring Boot 使用FastExcel实现多文件打包 ZIP导出
windows·spring boot·后端
ewenge27 分钟前
springboot+Selenium 实现html转图片(内含驱动包)
spring boot·selenium·html
Dolphin_Home1 小时前
Java Stream API 实战:电商业务高频操作全解析
java·网络·windows·spring boot
en-route1 小时前
Redis 作为消息队列的三种使用方式与 Spring Boot 实践
数据库·spring boot·redis
小坏讲微服务1 小时前
Spring Boot 4.0 + MyBatis-Plus 实战响应式编程的能力实战
java·spring boot·后端·mybatis
张较瘦_1 小时前
Springboot3 | JUnit 5 使用详解
spring boot·junit
李慕婉学姐1 小时前
Springboot遇见宠物生活馆系统设计与实现n6ea5118(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·宠物
BAStriver1 小时前
关于Flowable的使用小结
java·spring boot·spring·flowable
Dolphin_Home1 小时前
Java Stream 实战:订单商品ID过滤技巧(由浅入深)
java·开发语言·spring boot