Server-side HTML with Thymeleaf

Learn how to render an HTML page with Thymeleaf and Micronaut Views

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=views-thymeleaf,http-client,graalvm \
    --build=gradle \
    --lang=java \
    --test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add views-thymeleaf, http-client, and graalvm features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

5. Views

To use the Thymeleaf Java template engine to render views in a Micronaut application, add the following dependency on your classpath.

build.gradle
implementation("io.micronaut.views:micronaut-views-thymeleaf")

5.1. API Response

For this guide, we will use a publicly available REST API jsonplaceholder.typicode.com as a 3rd party Photo API.

Create a Photo record to map the API response:

src/main/java/example/micronaut/Photo.java
package example.micronaut;

import io.micronaut.core.annotation.ReflectiveAccess;
import io.micronaut.serde.annotation.Serdeable;

@Serdeable (1)
@ReflectiveAccess (2)
public record Photo(Long albumId, String title, String url, String thumbnailUrl) {
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
2 @ReflectiveAccess annotation that can be declared on a specific type, constructor, method or field to enable reflective access just for the annotated element.

Thymeleaf accesses Photo via reflection. By adding the @ReflectiveAccess annotation, the Micronaut Graal annotation processor generates the necessary reflection metadata to generate a Native Image with GraalVM.

5.2. HTTP Client

src/main/java/example/micronaut/PhotosClient.java
package example.micronaut;

import io.micronaut.core.annotation.Blocking;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import io.micronaut.http.client.annotation.Client;

@Client(id = "photos") (1)
public interface PhotosClient {

    @Get("/photos/{id}")(2)
    @Blocking
    Photo findById(@PathVariable Long id); (3)
}
1 Use @Client to use declarative HTTP Clients. You can annotate interfaces or abstract classes. You can use the id member to provide a service identifier or specify the URL directly as the annotation’s value.
2 The @Get annotation maps the findById method to an HTTP GET request on /photos/{id}.
3 You can define path variables with a RFC-6570 URI template in the HTTP Method annotation value. The method argument can optionally be annotated with @PathVariable.

5.3. HTTP Client Configuration

We used photos as the HTTP Client identifier.

Configure the micronaut.http.services.photos.url to point the client identifier to jsonplaceholder.typicode.com

src/main/resources/application.properties
micronaut.http.services.photos.url=https://jsonplaceholder.typicode.com

5.4. Controller

Create a controller, which invokes the declarative HTTP client:

src/main/java/example/micronaut/PhotosController.java
package example.micronaut;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import io.micronaut.http.annotation.Produces;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;
import io.micronaut.views.View;

import java.util.Collections;
import java.util.Map;

@Controller("/photos") (1)
public class PhotosController {

    private final PhotosClient photosClient;

    public PhotosController(PhotosClient photosClient) { (2)
        this.photosClient = photosClient;
    }

    @Produces(MediaType.TEXT_HTML) (3)
    @ExecuteOn(TaskExecutors.BLOCKING) (4)
    @View("photos/show.html") (5)
    @Get("/{id}") (6)
    Map<String, Photo> findById(@PathVariable Long id) { (7)
        return Collections.singletonMap("photo", photosClient.findById(id));
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /photos.
2 Use constructor injection to inject a bean of type PhotosClient.
3 Set the response content-type to HTML with the @Produces annotation.
4 It is critical that any blocking I/O operations (such as fetching the data from the database) are offloaded to a separate thread pool that does not block the Event loop.
5 Use View annotation to specify which template to use to render the response.
6 The @Get annotation maps the findById method to an HTTP GET request on /photos/{id}.
7 You can define path variables with a RFC-6570 URI template in the HTTP Method annotation value. The method argument can optionally be annotated with @PathVariable.

5.5. Thymeleaf template

Create a Thymeleaf template in src/main/resources/views/photos/show.html:

src/main/resources/views/photos/show.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Photo</title>
</head>
<body>
<h1 th:text="${photo.title}"></h1>
<a th:href="${photo.url}"><img th:src="${photo.thumbnailUrl}" th:alt="${photo.title}"/></a>
</body>
</html>

5.6. Tests

Write a test that verifies the application renders the HTML page.

src/test/java/example/micronaut/PhotosControllerTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.uri.UriBuilder;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import java.net.URI;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest (1)
class PhotosControllerTest {

    @Test
    void photoTest(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        URI uri  = UriBuilder.of("/photos").path("1").build();
        HttpRequest<?> request = HttpRequest.GET(uri).accept(MediaType.TEXT_HTML);
        String html = assertDoesNotThrow(() -> client.retrieve(request));
        assertNotNull(html);
        assertTrue(html.contains("<!DOCTYPE html>"));
        String expectedUrl = "https://via.placeholder.com/600/92c952";
        String expectedTitle = "accusamus beatae ad facilis cum similique qui sunt";
        String expectedThumbnailUrl = "https://via.placeholder.com/150/92c952";
        assertTrue(html.contains("<h1>" + expectedTitle + "</h1>"));
        assertTrue(html.contains("<a href=\"" + expectedUrl + "\"><img src=\"" + expectedThumbnailUrl + "\" alt=\"" + expectedTitle + "\"/></a>"));
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.

6. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

7. Native Tests

The io.micronaut.application Micronaut Gradle Plugin automatically integrates with GraalVM by applying the Gradle plugin for GraalVM Native Image building.

This plugin supports running tests on the JUnit Platform as native images. This means that tests will be compiled and executed as native code.

To execute the tests, execute:

./gradlew nativeTest

Then open build/reports/tests/test/index.html in a browser to see the results.

INFO: A test may be disabled within a GraalVM native image via the @DisabledInNativeImage annotation.

8. Next Steps

Explore more features with Micronaut Guides.

Read more about Micronaut Views.

9. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

10. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).