进阶SpringBoot之 Web 静态资源导入

idea 创建一个 web 项目

新建 controller 包下 Java 类,用来查验地址是否能成功运行

java 复制代码
package com.demo.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World";
    }
}

初始 resources 目录下

static 包下放静态资源

templates 包下放模板

分析源码:

双击 shift 搜索 WebMvcAutoConfiguration,找到 addResourceHandlers 方法

可以看到 getWebjarsPathPattern() 方法路径 classpath:/META-INF/resources/webjars/

java 复制代码
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                this.addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(), "classpath:/META-INF/resources/webjars/");
                this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
                    registration.addResourceLocations(this.resourceProperties.getStaticLocations());
                    if (this.servletContext != null) {
                        ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                        registration.addResourceLocations(new Resource[]{resource});
                    }

                });
            }
        }
WebJars

WebJars 是打包到 JAR(Java Archive)文件中的客户端 Web 库(例如 jQuery 和 Bootstrap)

pom.xml 导入依赖:

XML 复制代码
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.7.1</version>
        </dependency>

导入成功

点进 getStaticPathPattern() 获得静态资源的路径方法,/** 表示当前目录下全都识别

java 复制代码
private String staticPathPattern = "/**";

WebMvcProperties.class:

以下目录都能访问

resources 目录下新建一个 public 包,写个 1.js,随便写个 hello

启动后直接访问 localhost:8080/1.js,显示 hello

总结:

在 SpringBoot 中,可以使用以下方式处理静态资源:

  1. webjars

  2. public

  3. static(默认)

  4. /**

  5. resources

其中,优先级顺序:

resources > static > public

相关推荐
心之伊始1 分钟前
Dubbo 3 Consumer 调用链路源码分析:从 Proxy 到 Cluster、Directory、Router、LoadBalance
java·微服务·dubbo·源码分析·服务治理
我认不到你3 分钟前
【开源、教程】RAG全流程实现(java+完整代码):第一弹
java·开发语言·人工智能·深度学习·ai·语言模型·开源
程序员小羊!5 分钟前
16 JAVA MySQL 8.0
java·开发语言·mysql
放下华子我只抽RuiKe55 分钟前
FastAPI 全栈后端(五):后台任务与消息队列
前端·javascript·react.js·ai·前端框架·fastapi·ai编程
西凉的悲伤5 分钟前
Spring Boot 中 RedisTemplate 与 StringRedisTemplate 常用 Redis API 速查
spring boot·redis·后端·redistemplate·stringredis
丷丩5 分钟前
MapLibre GL JS第44课:生成并添加缺失图标
前端·javascript·gis·mapblibre gl js
ywl4708120877 分钟前
IDEA 集成 Claude Code (Beta)
java·ide·intellij-idea
wyhwust9 分钟前
web应用技术--springboot01
java·开发语言
lulu121654407810 分钟前
GPT-5.6 vs Claude Fable 5/Mythos 深度技术对比:kindle/kepler/Levi三版本实测全解析
java·人工智能·python·gpt
snow@li11 分钟前
前端:下拉框里边的数据叫啥 / 怎么称呼
前端