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

相关推荐
南山十一少36 分钟前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
bin91532 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
427724002 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo2 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦3 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个3 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
晴空万里藏片云3 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一3 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
Tirzano3 小时前
springsecurity自定义认证
spring boot·spring
奶球不是球3 小时前
el-button按钮的loading状态设置
前端·javascript