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。

相关推荐
崎岖Qiu8 分钟前
【SpringAI篇01】:5分钟教会你使用SpringAI (1.0.0稳定版)
java·spring boot·后端·spring·ai
摇滚侠2 小时前
Spring Boot3零基础教程,Profile 环境隔离用法,笔记55
java·spring boot·笔记
摇滚侠7 小时前
Spring Boot3零基础教程,函数式 Web 新特性,笔记51
java·spring boot·笔记
执笔论英雄8 小时前
【大模型推理】ScheduleBatch 学习
java·spring boot·学习
Slow菜鸟10 小时前
SpringBoot集成Elasticsearch | Elasticsearch 7.x专属HLRC(High Level Rest Client)
spring boot·elasticsearch·jenkins
Slow菜鸟10 小时前
SpringBoot教程(安装篇):Elasticsearch及可视化工具安装(Windows环境)
spring boot·elasticsearch
忧郁的橙子.10 小时前
IntelliJ IDEA 2023中为 Spring Boot 项目添加注释模板
java·spring boot·intellij-idea
聆风吟º10 小时前
【Spring Boot 报错已解决】别让端口配置卡壳!Spring Boot “Binding to target failed” 报错解决思路
android·java·spring boot
遥远_21 小时前
Spring Boot微服务健康检测:保障系统稳定性的关键实践
spring boot·微服务·1024程序员节·健康检测
苹果醋321 小时前
学习札记-Java8系列-1-Java8新特性简介&为什么要学习Java8
java·运维·spring boot·mysql·nginx