进阶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

相关推荐
醉城夜风~3 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
CHNE_TAO_EMSM4 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
数智化转型推荐官4 小时前
2026统一身份管理系统五大发展趋势解读
java·运维·微服务
看菜鸡互5 小时前
探索用 SlideML 让大模型生成 PPT 的实验方法
java·运维
一孤程5 小时前
Airtest自动化测试第五篇:小程序与Web测试——跨平台自动化全覆盖
前端·自动化测试·小程序·自动化·测试·airtest
IT_陈寒5 小时前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
yume_sibai6 小时前
大屏数据可视化 - 边框红绿呼吸灯实现详解
前端·信息可视化·typescript
Hyyy6 小时前
很多Desktop都在上的Computer Use是什么
前端·llm
慢功夫6 小时前
开篇:VS Code 为什么不是一个普通 React App
前端·visual studio code
ZhengEnCi6 小时前
S02-SpringBoot实体类新增字段对已有数据的影响及自动DDL同步机制详解
数据库·spring boot