在 Spring Boot 中使用 WebJars 是一种将前端资源(如 jQuery、Bootstrap、Vue.js 等)以 JAR 包形式引入项目并自动通过 HTTP 访问的便捷方式

张开发
2026/4/22 17:22:24 15 分钟阅读
在 Spring Boot 中使用 WebJars 是一种将前端资源(如 jQuery、Bootstrap、Vue.js 等)以 JAR 包形式引入项目并自动通过 HTTP 访问的便捷方式
在 Spring Boot 中使用 WebJars 是一种将前端资源如 jQuery、Bootstrap、Vue.js 等以 JAR 包形式引入项目并自动通过 HTTP 访问的便捷方式。WebJars 将静态资源CSS、JS、字体等打包为标准 Maven/Gradle 依赖Spring Boot 的spring-boot-starter-web默认集成了对 WebJars 的支持通过WebMvcAutoConfiguration和ResourceHandlerRegistry自动配置/webjars/**路径映射。✅使用步骤如下添加 WebJars 依赖以 Maven 为例!-- 例如引入 Bootstrap 5 --dependencygroupIdorg.webjars/groupIdartifactIdbootstrap/artifactIdversion5.3.3/version/dependency!-- 可选WebJars 官方提供的 jQuery --dependencygroupIdorg.webjars/groupIdartifactIdjquery/artifactIdversion3.7.1/version/dependency在 HTML 模板中引用资源以 Thymeleaf 为例!DOCTYPEhtmlhtmlxmlns:thhttp://www.thymeleaf.orgheadlinkth:href{/webjars/bootstrap/5.3.3/css/bootstrap.min.css}relstylesheet//headbodyscriptth:src{/webjars/jquery/3.7.1/jquery.min.js}/scriptscriptth:src{/webjars/bootstrap/5.3.3/js/bootstrap.bundle.min.js}/script/body/html✅ 注意路径格式/webjars/{artifactId}/{version}/{path}Spring Boot 自动解析该路径到对应 JAR 包内的META-INF/resources/webjars/{artifactId}/{version}/...可选启用 WebJars 资源链提升缓存与版本管理ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){registry.addResourceHandler(/webjars/**).resourceChain(true).addResolver(newWebJarsResourceResolver());}}WebJarsResourceResolver可自动处理版本号如/webjars/bootstrap/css/bootstrap.css→ 解析为带版本的实际路径配合ResourceUrlEncodingFilter还可在 Thymeleaf 中使用{/webjars/bootstrap/css/bootstrap.css}自动生成带哈希或版本的 URL。⚠️ 注意事项Spring Boot 2.4 默认禁用classpath:/static/和classpath:/templates/外的资源自动注册但/webjars/**是白名单路径无需额外配置。若使用 Spring Security需确保/webjars/**路径被放行如.requestMatchers(/webjars/**).permitAll()。推荐使用 https://www.webjars.org 查询可用版本和坐标。// 示例Controller 中验证 WebJars 是否生效可选GetMapping(/test-webjar)ResponseBodypublicStringtestWebJar(){returnCheck /webjars/jquery/3.7.1/jquery.min.js in browser;}Utilizing WebJars in Spring BootWelcome to 2014! 2013 was an exciting year for Spring, and we look forward to another great year. We have focused on client-side development in a few recent posts, including that we have published several new client-side getting started guides. In a previous post, I also reviewed how easy it is to serve static web content with Spring Boot.In this post I will continue the discussion about client-side development with Spring Boot as we explore another built-in capability. My previous post included the following excerpt from the source code for WebMvcAutoConfiguration which illustrates how static resources are automatically added to a Spring MVC ResourceHandlerRegistry when using Spring Boot.Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {if (!registry.hasMappingForPattern(“/webjars/“)) {registry.addResourceHandler(”/webjars/”).addResourceLocations(“classpath:/META-INF/resources/webjars/”);}if (!registry.hasMappingForPattern(“/“)) {registry.addResourceHandler(”/”).addResourceLocations(RESOURCE_LOCATIONS);}}One aspect of this code I did not discuss in the last post is the “webjars” resource handler. You may be thinking, “That’s nice, but what are webjars?”.As a Java developer, you are probably familiar with the JAR (Java Archive) file format, which is used to package many class files and their associated metadata into a single file. WebJars is simply taking the concept of a JAR and applying it to client-side libraries or resources. For example, the jQuery library may be packaged as a JAR and made available to your Spring MVC application. There are several benefits to using WebJars, including support for Java build tools such as Gradle and Maven. And by using dependency management in a build tool, transitive dependencies are automatically handled for you.Perhaps you want to add a jQuery animation to your web page. Using the Serving Web Content with Spring MVC guide as a starting point, modify the build.gradle file to include the jQuery dependency. Many WebJars are available through Maven Central with a GroupID of org.webjars. A complete list is available at webjars.org.buildscript {repositories {maven { url “http://repo.spring.io/libs-milestone” }mavenLocal()}dependencies {classpath(“org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M6”)}}apply plugin: ‘java’apply plugin: ‘eclipse’apply plugin: ‘idea’apply plugin: ‘spring-boot’jar {baseName ‘gs-serving-web-content’version ‘0.1.0’}repositories {mavenCentral()maven { url “http://repo.spring.io/libs-milestone” }}dependencies {compile(“org.springframework.boot:spring-boot-starter-web:0.5.0.M6”)compile(“org.thymeleaf:thymeleaf-spring3:2.0.17”)compile(“org.webjars:jquery:2.0.3-1”)testCompile(“junit:junit:4.11”)}task wrapper(type: Wrapper) {gradleVersion ‘1.8’}After you add the dependency, you can reference the jQuery WebJar in your HTML and utilize it to animate the text in the paragraph tag. Note the location of the jQuery dependency!Getting Started: Serving Web ContentJavaScript package management is not a new concept. Indeed, npm and bower are two of the more popular tools, and currently offer solutions to managing JavaScript dependencies. Spring’s Understanding JavaScript Package Managers guide has more information on these. Most JavaScript developers are likely familiar with npm and bower and make use of those in their projects. In contrast, WebJars utilizes Maven’s dependency management model to include JavaScript libraries in a project, making it more accessible to Java developers.Spring Boot offers an easy way to build Spring applications that require little or no configuration. This post illustrates how simple it is to use WebJars in your Spring MVC application, and how WebJars provide a convenient way of managing JavaScript packages and dependencies. For more information see the Spring Boot project page and the catalog of getting started guides.comments powered by Disqus

更多文章