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

相关推荐
lkbhua莱克瓦244 分钟前
Java练习——数组练习
java·开发语言·笔记·github·学习方法
趙卋傑6 分钟前
常见排序算法
java·算法·排序算法
Slow菜鸟12 分钟前
Java后端常用技术选型 |(四)微服务篇
java·分布式
BBB努力学习程序设计16 分钟前
了解响应式Web设计:viewport网页可视区域
前端·html
武子康18 分钟前
Java-168 Neo4j CQL 实战:WHERE、DELETE/DETACH、SET、排序与分页
java·开发语言·数据库·python·sql·nosql·neo4j
zhangyao94033018 分钟前
uni-app scroll-view特定情况下运用
前端·javascript·uni-app
Filotimo_18 分钟前
SpringBoot3入门
java·spring boot·后端
码农张19 分钟前
从原理到实践,吃透 Lit 响应式系统的核心逻辑
前端
jump68019 分钟前
object和map 和 WeakMap 的区别
前端
打小就很皮...25 分钟前
基于 Dify 实现 AI 流式对话:组件设计思路(React)
前端·react.js·dify·流式对话