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。

相关推荐
Coder_Boy_3 小时前
SpringAI与LangChain4j的智能应用-(理论篇2)
人工智能·spring boot·langchain·springai
Coder_Boy_3 小时前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
武昌库里写JAVA4 小时前
iview-CRUD模板
vue.js·spring boot·sql·layui·课程设计
楼兰胡杨5 小时前
Spring Boot整合Sentinel之QPS限流
spring boot
Coder_Boy_6 小时前
基于SpringAI的智能平台基座开发-(四)
java·人工智能·spring boot·langchain·springai
码界奇点6 小时前
基于Spring Boot的内容管理系统框架设计与实现
java·spring boot·后端·车载系统·毕业设计·源代码管理
乐韵天城8 小时前
SpringBoot中如何手动开启数据库事务
数据库·spring boot
墨着染霜华9 小时前
Spring Boot整合Kaptcha生成图片验证码:新手避坑指南+实战优化
java·spring boot·后端
我爱学习好爱好爱9 小时前
Prometheus监控栈 监控java程序springboot
java·spring boot·prometheus
老华带你飞9 小时前
考试管理系统|基于java+ vue考试管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端