Skip to main content

Command Palette

Search for a command to run...

WebJars Basics

Published
2 min read
WebJars Basics

Introduction

WebJars are a way to package client-side web libraries, such as JavaScript and CSS frameworks, into JAR (Java Archive) files. The primary purpose is to manage these web resources using standard JVM build tools like Maven, Gradle, or SBT, rather than with separate JavaScript package managers like npm. This approach simplifies dependency management for JVM-based web applications, as the client and server dependencies are handled through the same system.

How WebJars work

A WebJar is essentially a standard .jar file containing web assets in the META-INF/resources/webjars/ directory. When you add a WebJar dependency to your project, the build tool automatically downloads it from a repository like Maven Central. A Servlet 3.0-compliant web container will then serve the included resources as static content.

For example, to include a WebJar for jQuery, you would add a dependency to your Maven pom.xml:

xml

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>

Use code with caution.

You can then reference the library in your HTML file like this, where the framework handles the pathing automatically:

html

<script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}"></script>

Use code with caution.

Benefits of using WebJars

  • Centralized dependency management: You can manage all project dependencies---both client-side (JavaScript, CSS) and server-side (Java libraries)---using a single build tool like Maven or Gradle.
  • Version control: WebJars provide declarative versioning, ensuring a consistent and predictable version of a library across your entire project.
  • Simplified updates: To upgrade a client-side library, you only need to change the version number in your build file. With some frameworks, a version-agnostic lookup can be used so you don't even need to update the path in your front-end code.
  • Transitive dependencies: Your build tool automatically handles transitive dependencies. If you include Bootstrap, the required jQuery library is automatically included as well.
  • Simplified builds: You no longer need to manually download or copy and paste web library files into your project, which streamlines the build process.
  • Offline development: Once the WebJar is downloaded by your build tool, you can work on your project offline without needing access to a public CDN for your client-side libraries.

More from this blog

Cloud Tuned

627 posts

Your starting point for anything cloud: AWS, Azure, GCP, Serverless, Architecture, Hybrid Cloud, Systems Design and other Information Technology topics.