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。

相关推荐
一点程序3 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
奋进的芋圆5 小时前
Spring Boot 实现三模安全登录:微信扫码 + 手机号验证码 + 邮箱验证码
spring boot·redis·微信
怪兽源码5 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
m0_740043738 小时前
【无标题】
java·spring boot·spring·spring cloud·微服务
重整旗鼓~8 小时前
1.外卖项目介绍
spring boot
一点技术10 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
shuair10 小时前
redis实现布隆过滤器
spring boot·redis·bootstrap
RANCE_atttackkk10 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
好好研究12 小时前
Spring Boot - Thymeleaf模板引擎
java·spring boot·后端·thymeleaf
她说..12 小时前
策略模式+工厂模式实现单接口适配多审核节点
java·spring boot·后端·spring·简单工厂模式·策略模式