SpringBoot - WebJars

简介: SpringBoot - WebJars

【1】是什么


WebJars是将web前端资源(js,css等)打成jar包文件,然后借助Maven工具,以jar包形式对web前端资源进行统一依赖管理,保证这些Web资源版本唯一性。WebJars的jar包部署在Maven中央仓库上。


20180613112115734.jpg


【2】WebJars使用

在官网首页,找到资源文件对应的maven依赖,写入项目pom.xml文件,然后在页面引用即可。


如下图所示,引入JQuery和Bootstrap:

pom.xml文件如下所示:

<!--引入jquery-webjar-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!--引入bootstrap-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.0.0</version>
        </dependency>

引入的jar包如下:


【3】SpringBoot对WebJars支持

查看WebMWebMVCAutoConfiguration源码如下:

@Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            //注意这里,对webjars支持
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler("/webjars/**")
                                .addResourceLocations(
                                        "classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(cachePeriod));
            }
            //这里是对静态资源的映射支持
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(
                                        this.resourceProperties.getStaticLocations())
                        .setCachePeriod(cachePeriod));
            }
        }

其中如下代码说明SpringBoot如何对WebJars进行支持:

所有 /webjars/**都去 classpath:/META-INF/resources/webjars/ 找资源

//注意这里,对webjars支持
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations(
                        "classpath:/META-INF/resources/webjars/")
        .setCachePeriod(cachePeriod));
}

【4】页面使用

页面引入如下:

<link rel="stylesheet" href="/webjars/bootstrap/4.0.0/css/bootstrap.css" />
<script src="/webjars/jquery/3.3.1/jquery.js"></script>
<script src="/webjars/bootstrap/4.0.0/js/bootstrap.js"></script>

如上所示,路径中是需要添加版本号的,这是很不友好的,下面去掉版本号。

pom.xml添加依赖如下:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.32</version>
</dependency>

对应的类-WebJarsResourceResolver如下:

  • WebJarsResourceResolver 的作用是可以让页面引用省略 webjar 的版本。
package org.springframework.web.servlet.resource;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.webjars.WebJarAssetLocator;
import org.springframework.core.io.Resource;
/**
 * A {@code ResourceResolver} that delegates to the chain to locate a resource and then
 * attempts to find a matching versioned resource contained in a WebJar JAR file.
 *
 * <p>This allows WebJars.org users to write version agnostic paths in their templates,
 * like {@code <script src="/jquery/jquery.min.js"/>}.
 * This path will be resolved to the unique version {@code <script src="/jquery/1.2.0/jquery.min.js"/>},
 * which is a better fit for HTTP caching and version management in applications.
 *
 * <p>This also resolves resources for version agnostic HTTP requests {@code "GET /jquery/jquery.min.js"}.
 *
 * <p>This resolver requires the "org.webjars:webjars-locator" library on classpath,
 * and is automatically registered if that library is present.
 *
 * @author Brian Clozel
 * @since 4.2
 * @see org.springframework.web.servlet.config.annotation.ResourceChainRegistration
 * @see <a href="http://www.webjars.org">webjars.org</a>
 */
public class WebJarsResourceResolver extends AbstractResourceResolver {
    private final static String WEBJARS_LOCATION = "META-INF/resources/webjars/";//默认去该路径下寻找
    private final static int WEBJARS_LOCATION_LENGTH = WEBJARS_LOCATION.length();
    private final WebJarAssetLocator webJarAssetLocator;
    /**
     * Create a {@code WebJarsResourceResolver} with a default {@code WebJarAssetLocator} instance.
     */
    public WebJarsResourceResolver() {
        this(new WebJarAssetLocator());
    }
    /**
     * Create a {@code WebJarsResourceResolver} with a custom {@code WebJarAssetLocator} instance,
     * e.g. with a custom index.
     * @since 4.3
     */
    public WebJarsResourceResolver(WebJarAssetLocator webJarAssetLocator) {
        this.webJarAssetLocator = webJarAssetLocator;
    }
    @Override
    protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath,
            List<? extends Resource> locations, ResourceResolverChain chain) {
        Resource resolved = chain.resolveResource(request, requestPath, locations);
        if (resolved == null) {
            String webJarResourcePath = findWebJarResourcePath(requestPath);
            if (webJarResourcePath != null) {
                return chain.resolveResource(request, webJarResourcePath, locations);
            }
        }
        return resolved;
    }
    @Override
    protected String resolveUrlPathInternal(String resourceUrlPath,
            List<? extends Resource> locations, ResourceResolverChain chain) {
        String path = chain.resolveUrlPath(resourceUrlPath, locations);
        if (path == null) {
            String webJarResourcePath = findWebJarResourcePath(resourceUrlPath);
            if (webJarResourcePath != null) {
                return chain.resolveUrlPath(webJarResourcePath, locations);
            }
        }
        return path;
    }
    // 这里获取请求对应的项目中实际资源路径,
    //返回结果如:bootstrap/4.0.0/css/bootstrap.css
    protected String findWebJarResourcePath(String path) {
        int startOffset = (path.startsWith("/") ? 1 : 0);
        int endOffset = path.indexOf("/", 1);
        if (endOffset != -1) {
            String webjar = path.substring(startOffset, endOffset);
            String partialPath = path.substring(endOffset + 1);
            String webJarPath = webJarAssetLocator.getFullPathExact(webjar, partialPath);
            if (webJarPath != null) {
                return webJarPath.substring(WEBJARS_LOCATION_LENGTH);
            }
        }
        return null;
    }
}

页面引用修改如下:

<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.css" />
<script src="/webjars/jquery/jquery.js"></script>
<script src="/webjars/bootstrap/js/bootstrap.js"></script>

此时,使用两种形式(带版本号和不带版本号)的请求都可以正确获取资源!

目录
相关文章
|
11月前
|
JavaScript 前端开发 Java
SpringBoot_web开发-webjars&静态资源映射规则
https://www.91chuli.com/ 举例:jquery前端框架
148 0
|
前端开发 Java Maven
Spring Boot入门(十二) 之 前端静态资源的引入 (webjars 以及 thymeleaf 视图解析器)
Spring Boot入门(十二) 之 前端静态资源的引入 (webjars 以及 thymeleaf 视图解析器)
308 0
|
前端开发 JavaScript Java
SpringBoot2.x基础篇:将静态资源打包为WebJars
我们在编写前后分离项目时,前端的项目一般需要静态资源(`Image`、`CSS`、`JavaScript`...)来进行渲染界面,而如果我们对外采用依赖的方式提供使用时,我们的静态资源文件也应该放入打包文件内,这样才能更便捷的提供我们的功能,在我的开源分布式日志框架 [minbox-logging](https://gitee.com/minbox-projects/minbox-logging) 内提供了管理界面的功能,就是采用的这种方式实现,将静态资源以及**编译后**的`HTML`页面存放到`minbox-logging-admin-ui`依赖内,下面我们来看下具体的实现方式。
|
前端开发 JavaScript Java
SpringBoot使用WebJars
本人主要做的是java,但是从第一份工作开始,就一直在做一个写前端又写后端的程序员,相信很多朋友和我一样,不仅要会后台代码,还要懂得很多的前端代码,例如javascipt和css样式。
2746 0
|
20天前
|
前端开发 安全 Java
基于springboot+vue开发的会议预约管理系统
一个完整的会议预约管理系统,包含前端用户界面、管理后台和后端API服务。 ### 后端 - **框架**: Spring Boot 2.7.18 - **数据库**: MySQL 5.6+ - **ORM**: MyBatis Plus 3.5.3.1 - **安全**: Spring Security + JWT - **Java版本**: Java 11 ### 前端 - **框架**: Vue 3.3.4 - **UI组件**: Element Plus 2.3.8 - **构建工具**: Vite 4.4.5 - **状态管理**: Pinia 2.1.6 - **HTTP客户端
125 4
基于springboot+vue开发的会议预约管理系统
|
5月前
|
JavaScript 前端开发 Java
制造业ERP源码,工厂ERP管理系统,前端框架:Vue,后端框架:SpringBoot
这是一套基于SpringBoot+Vue技术栈开发的ERP企业管理系统,采用Java语言与vscode工具。系统涵盖采购/销售、出入库、生产、品质管理等功能,整合客户与供应商数据,支持在线协同和业务全流程管控。同时提供主数据管理、权限控制、工作流审批、报表自定义及打印、在线报表开发和自定义表单功能,助力企业实现高效自动化管理,并通过UniAPP实现移动端支持,满足多场景应用需求。
464 1
|
6月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
431 7
|
2月前
|
前端开发 JavaScript Java
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
本系统基于SpringBoot与Vue3开发,实现校园食堂评价功能。前台支持用户注册登录、食堂浏览、菜品查看及评价发布;后台提供食堂、菜品与评价管理模块,支持权限控制与数据维护。技术栈涵盖SpringBoot、MyBatisPlus、Vue3、ElementUI等,适配响应式布局,提供完整源码与数据库脚本,可直接运行部署。
100 0
基于springboot+vue开发的校园食堂评价系统【源码+sql+可运行】【50809】
|
5月前
|
供应链 JavaScript BI
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
这是一款专为小微企业打造的 SaaS ERP 管理系统,基于 SpringBoot+Vue+ElementUI+UniAPP 技术栈开发,帮助企业轻松上云。系统覆盖进销存、采购、销售、生产、财务、品质、OA 办公及 CRM 等核心功能,业务流程清晰且操作简便。支持二次开发与商用,提供自定义界面、审批流配置及灵活报表设计,助力企业高效管理与数字化转型。
478 2
ERP系统源码,基于SpringBoot+Vue+ElementUI+UniAPP开发
|
9月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。