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。

相关推荐
白仑色44 分钟前
Spring Cloud Gateway 实战指南
spring boot·微服务·路由转发·限流熔断
追风少年浪子彦7 小时前
mapstruct与lombok冲突原因及解决方案
java·spring boot·spring·spring cloud
军军君017 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis
白仑色9 小时前
完整 Spring Boot + Vue 登录系统
vue.js·spring boot·后端
MZ_ZXD0019 小时前
flask校园学科竞赛管理系统-计算机毕业设计源码12876
java·spring boot·python·spring·django·flask·php
小郭的学习日记11 小时前
互联网大厂Java面试:从Spring Boot到微服务的场景应用
spring boot·微服务·java面试·技术栈·电商平台
超级小忍11 小时前
在 Spring Boot 中使用 MyBatis 的 XML 文件编写 SQL 语句详解
xml·spring boot·mybatis
Q_Q196328847512 小时前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
超级小忍12 小时前
在 Spring Boot 中如何使用 Assert 进行断言校验
spring boot·后端