在 Web 应用中会涉及到大量的静态资源,例如 JS、CSS 和 HTML 等。我们知道,Spring MVC 导入静态资源文件时,需要配置静态资源的映射;但在 SpringBoot 中则不再需要进行此项配置,因为 SpringBoot 已经默认完成了这一工作。
        Spring Boot 默认为我们提供了 3 种静态资源映射规则:

  • WebJars 映射
  • 默认资源映射
  • 静态首页(欢迎页)映射

一、WebJars映射

1.为什么使用WebJars

        WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。

        我们在开发Java web项目的时候会使用像Maven,Gradle等构建工具以实现对jar包版本依赖管理,以及项目的自动化管理,但是对于JavaScript,Css等前端资源包,我们只能采用拷贝到webapp目录下的手工方式,这样做就无法对这些资源进行依赖管理。而且容易导致文件混乱、版本不一致等问题。那么WebJars就提供给我们这些前端资源的jar包形式,我们就可以进行依赖管理。

        WebJars是将这些通用的Web前端资源打包成Java的Jar包,然后借助Maven工具对其管理,保证这些Web资源版本唯一性,升级也比较容易。关于webjars资源,有一个专门的网站http://www.webjars.org/,我们可以到这个网站上找到自己需要的资源,在自己的工程中添加入maven依赖,即可直接使用这些资源了。

2.WebJars介绍及使用方法

        为了让页面更加美观,让用户有更多更好的体验,Web 应用中通常会使用大量的 JS 和 CSS,例如 jQuery,Backbone.js 和 Bootstrap 等等。通常我们会将这些 Web 前端资源拷贝到 Java Web 项目的 webapp 相应目录下进行管理。但是 Spring Boot 项目是以 JAR 包的形式进行部署的,不存在 webapp 目录,那么 Web 前端资源该如何引入到 Spring Boot 项目中呢?WebJars 可以完美的解决上面的问题,它可以 Jar 形式为 Web 项目提供资源文件。
        WebJars 可以将 Web 前端资源(JS,CSS 等)打成一个个的 Jar 包,然后将这些 Jar 包部署到 Maven 中央仓库中进行统一管理,当 Spring Boot 项目中需要引入 Web 前端资源时,只需要访问 WebJars 官网,找到所需资源的 pom 依赖,将其导入到项目中即可。         所有通过 WebJars 引入的前端资源都存放在当前项目类路径(classpath)下的“/META-INF/resources/webjars/” 目录中。

下图展示如何通过 WebJars 查找 JQuery 的 pom 依赖的过程。

java静态资源文件夹 java 静态资源映射_spring

        Spring Boot 通过 MVC 的自动配置类  WebMvcAutoConfiguration 为这些 WebJars 前端资源提供了默认映射规则,部分源码如下:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        //WebJars 映射规则
        this.addResourceHandler(registry, "/webjars/**", "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/**”,即所有访问“/webjars/**”的请求,都会去“classpath:/META-INF/resources/webjars/”查找 WebJars 前端资源。

3.项目举例

(1)项目框架

java静态资源文件夹 java 静态资源映射_spring_02

(2)代码实现

MainApplication.java:

package com.xj.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * @Author : xjfu
 * @Date : 2022/6/8 8:38
 * @Description :Spring Boot 启动类
 */
@ComponentScan("com.xj")
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

application.yml:

#默认配置
server:
    port: 8080

#切换配置
spring:
    profiles:
        active: dev #指定使用哪个profile

---
#开发环境
server:
    port: 8081

spring:
    config:
        activate:
            on-profile: dev
---
#测试环境
server:
    port: 8082

spring:
    config:
        activate:
            on-profile: test
---
#生产环境
server:
    port: 8083

spring:
    config:
        activate:
            on-profile: prod


logging:
    config: classpath:logback-spring.xml #指定使用哪个日志配置文件

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xj.study</groupId>
    <artifactId>spring-boot-study-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!--jquery引入-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.0</version>
        </dependency>
    </dependencies>

    <!--build标签描述了如何来编译及打包项目,而具体的编译和打包工作是通过build中配置的 plugin 来完成-->
    <build>
        <plugins>
            <!--使用SpringBoot的打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

因为是拿jquer为例,所以pom.xml导入了其对应的Jar包:

<!--jquery引入-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.0</version>
        </dependency>

(3)运行结果

java静态资源文件夹 java 静态资源映射_spring boot_03

二、默认资源映射

        当访问项目中的任意资源(即“/**”)时,Spring Boot 会默认从以下路径中查找资源文件(优先级依次降低):

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/

        这些路径又被称为静态资源文件夹,它们的优先级顺序为:classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/ 。
        当我们请求某个静态资源(即以“.html”结尾的请求)时,Spring Boot 会先查找优先级高的文件夹,再查找优先级低的文件夹,直到找到指定的静态资源为止。

1.项目举例

(1)项目架构

java静态资源文件夹 java 静态资源映射_spring_04

(2)代码实现

 MainApplication.java:

(同上)

application.yml:

(同上)

pom.xml:

(同上)

hello.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>默认静态资源映射</title>
</head>
<body>
<h1>唉,注定要一个人孤独终老喽……</h1>
</body>
</html>

(3)运行结果

java静态资源文件夹 java 静态资源映射_html_05

三、静态首页(欢迎页)映射

        静态资源文件夹下的所有 index.html 被称为静态首页或者欢迎页,它们会被被 /** 映射,换句话说就是,当我们访问“/”或者“/index.html”时,都会跳转到静态首页(欢迎页)。

注意,访问静态首页或欢迎页时,其查找顺序也遵循默认静态资源的查找顺序,即先查找优先级高的目录,在查找优先级低的目录,直到找到 index.html 为止。

1.项目举例

(1)项目架构

java静态资源文件夹 java 静态资源映射_spring_06

 (2)代码实现

MainApplication.java:

(同上)

application.yml:

(同上)

pom.xml:

(同上)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>静态首页(欢迎页)映射</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>

(3) 运行结果

java静态资源文件夹 java 静态资源映射_spring_07

四、参考

1.Spring Boot静态资源映射