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/**
相关推荐
贾斯汀玛尔斯7 小时前
每天学一个算法--LSM-Tree(Log-Structured Merge Tree)
java·算法·lsm-tree
bitt TRES7 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
Y001112367 小时前
JavaWeb-end
java·servlet·web
万少7 小时前
Vibe Coding不停歇,移动端 TRAE SOLO 让你用手机也能编程啦
前端·javascript·后端
bzmK1DTbd7 小时前
Git版本控制:Java项目中的分支管理与合并策略
java·开发语言·git
Rust研习社8 小时前
为什么 Rust 没有空指针?
开发语言·后端·rust
皮皮林5518 小时前
全网最全的 Jenkins + Maven + Git 自动化部署指南!
后端
舒一笑8 小时前
用几十行代码搞定 Chat 接口透明转发:跨环境轻量级网关实战
后端·程序员·架构
铁皮饭盒9 小时前
成为AI全栈 - 第3课:路由 RESTful Elysia 状态码 设计规范
前端·后端·全栈
我叫黑大帅9 小时前
如何通过 Python 实现招聘平台自动投递
后端·python·面试