Spring Boot htmx Thymeleaf - Hello World Example

In this section, we will build a simple 'hello world' web application with Spring Boot, htmx, and, Thymeleaf.

Technologies Used

  • Java 17
  • Spring Boot 3.3.0
  • Thymeleaf 
  • htmx
  • Bootstrap

 

About htmx

HTMX is a small JavaScript library that allows us to use custom attributes within the HTML code that execute an Ajax request and integrate the result into the DOM. This makes it ideal for server-side rendering with Thymeleaf and Spring Boot.

htmx enables the development of web applications that have the feel of SPA (Single-page application). 

With the ease and power of hypertext, htmx allows you to create modern user interfaces by enabling you to leverage not just AJAX but also CSS Transitions, WebSockets, and Server Sent Events directly in HTML through the usage of attributes.

More Info: https://spring.io/blog/2024/03/15/hypermedia-and-browser-enhancement#htmx

The simplest way to do that would be to grab it from a CDN:

<script src='https://unpkg.com/htmx.org/dist/htmx.min.js'></script>


Instead of this, in this example we are using Webjars to load the library into the classpath, that would work as well.

Maven:

<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>htmx.org</artifactId>
<version>1.9.12</version>
</dependency>


Gradle:

implementation group: 'org.webjars.npm', name: 'htmx.org', version: '1.9.12'


Then, we can use the @{/webjars/htmx.org/… path for static content, served from Webjar.

<script th:src="@{/webjars/htmx.org/1.9.12/dist/htmx.min.js}" defer></script>


Complete example

Let's begin,

Creating a spring boot application

First, open the Spring initializr https://start.spring.io

Then, Provide the Group and Artifact name. We have provided Group name com.knf.dev.demo and Artifact spring-boot-htmx-helloworld. Here I selected the Maven project - language Java 17 - Spring Boot 3.3.0, Spring Web, and Thymeleaf.


Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(spring-boot-htmx-helloworld) file and downloads the project. Then, Extract the Zip file. 

Then, import the project on your favourite IDE. 


Final Project Directory


Add htmx and Bootstrap WebJars.

      <dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>htmx.org</artifactId>
<version>1.9.12</version>
</dependency>


Complete 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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-boot-htmx-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-htmx-helloworld</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>htmx.org</artifactId>
<version>1.9.12</version>
</dependency>

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

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


Create a Spring MVC Controller

package com.knf.dev.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class HomeController {

@GetMapping("/")
public String index() {
return "index";
}

@PostMapping("/info")
public String info() {
return "info";
}

}


Create index.html

Let's prepare a simple template for our index page. 
Add some logic to our hyperlink, which will call the second endpoint of our controller and replace our 'Home' text.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Indexpage</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link th:href="@{/webjars/bootstrap/5.3.3/css/bootstrap.min.css}"
rel="stylesheet" />
<script th:src="@{/webjars/bootstrap/5.3.3/js/bootstrap.bundle.min.js}"
defer></script>
<script th:src="@{/webjars/htmx.org/1.9.12/dist/htmx.min.js}"
defer></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand"
th:hx-post="@{/info}"
hx-trigger="click"
hx-target="#info"
href="#">Info</a>
</div>
</nav>
<h1 class="mb-4" id="info">Home</h1>
</body>
</html>

Here we created the link to our endpoint, which will be contained in the hx-post attribute. On click, htmx will now call the endpoint via Ajax and replace our targeted <h1> element with the response. 


Create info.html

<h1 class="mb-4">Info</h1>


Run the application - Application.java

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Run the Spring Boot application - mvn spring-boot:run


OR 


Run this Spring boot application from 

  • IntelliJ IDEA IDE by right click - Run 'Application.main()' 
  • Eclipse/STS - You can right click the project or the Application.java file and run as java application or Spring boot application.

Access URL via browser: http://localhost:8080

Clicking on the link 'Info', which will call the second endpoint of our controller and replace our 'Home' text with 'Info' text.

Source code - click here!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete