springBoot--静态资源映射

静态资源映射

  • 前言
  • [1、通过继承 WebMvcConfigurerAdapter 来实现](#1、通过继承 WebMvcConfigurerAdapter 来实现)
  • [2、在 application.properties 配置](#2、在 application.properties 配置)

前言

在 web 开发中,静态资源的访问是必不可少的,如图片、js、css等资源的访问

1、通过继承 WebMvcConfigurerAdapter 来实现

即如果使用了 @EnableWebMvc ,则自动配置类 WebMvcAutoConfiguration 会失效,因此默认映射路径 /static , /public , META-INF/resources , /resources 都将失效

java 复制代码
package com.example.ruiji_demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author jitwxs
 * @date 2024年03月10日 20:52
 */
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
//    设置静态资映射
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry){
        log.info("开始进行静态资源映射");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates").addResourceLocations("classPath:/templates/");
    }
}

2、在 application.properties 配置

java 复制代码
spring.mvc.static-path-pattern=/static/**
相关推荐
雨中飘荡的记忆10 分钟前
Spring状态机深度解析
java·后端·spring
BBB努力学习程序设计12 分钟前
Java记录类(Records)与数据建模革命:从POJO到不可变数据的范式转变
java
月屯18 分钟前
Pandoc 之--pdf-engine
java·开发语言·pdf
10km24 分钟前
java: HashMap.merge 的 Null 值陷阱:为什么 Stream API 会抛出 NPE
java·stream·hashmap·merge
晨星33426 分钟前
使用 IntelliJ IDEA 轻松连接 Java 与 MySQL 8 数据库
java·开发语言·数据库
睡觉早点26 分钟前
IntelliJ IDEA下载安装过程(含Java环境搭建)
java·ide·jdk·maven·intellij-idea
李少兄27 分钟前
IntelliJ IDEA Maven 工具栏消失怎么办?
java·maven·intellij-idea
草酸艾司西酞普兰28 分钟前
idea中使用Qoder插件
java·ide·intellij-idea
芽芽_029 分钟前
idea无法打开:Cannot collect JVM options
java·ide·intellij-idea
Flying_Fish_roe30 分钟前
IntelliJ IDEA 2025 版本与其他历史版本的全面专业对比分析
java·ide·intellij-idea