(This post has been updated at blog.hcf.dev with a later version of Spring Boot.)
This series of articles will examine Spring Boot features. This second article builds on the first article by demonstrating how to serve static resources from the classpath
and WebJars.
Complete source code for the series and for this part are available on Github.
Static Resources
By default, resources found on the classpath
under /static
are served. This is demonstrated by creating ${project.basedir}/src/main/resources/static/index.html
:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
Starting the application as described in part 1 and browsing http://localhost:8080/ produces something similar to:
Note: No additional Java code is required to serve static resources.
WebJars
WebJars are client-side web libraries packaged into JAR (Java Archive) files. Developers can use JVM build tools (e.g., Maven and Gradle) may be used to download and manage client-side dependencies.
To use this feature:
Add
org.webjars:webjars-locator-core
(version specified in the parent POM) so Spring Boot finds it on the runtimeclasspath
and enables the featureAdd the WebJars as dependencies
The POM has been so modified to provide Bulma.
<project>
...
<dependencies>
...
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
...
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>bulma</artifactId>
<version>0.9.2</version>
</dependency>
...
</dependencies>
...
</project>
After adding the corresponding stylesheet link to ${project.basedir}/src/main/resources/static/index.html
:
...
<head>
<link rel="stylesheet" href="/webjars/bulma/css/bulma.css"/>
</head>
...
And browsing http://localhost:8080/ shows the integration of the Bulma styles.
One additional feature is the developer does not need to be concerned with the frontend versions when linking into HTML. The org.webjars:webjars-locator-core
serves bulma.css
at both http://localhost:8080/webjars/bulma/0.9.2/css/bulma.css and http://localhost:8080/webjars/bulma/css/bulma.css.
Note: Again, no additional Java code is required to serve static resources.
Summary
This article demonstrates how static resources may be provided to be served by the Spring Web Server. These resources may be included on the classpath
under the /static
folder or within WebJars.
Part 3 of this series discusses dependency injection and implements a simple @RestController
.
Top comments (0)