Introduction

In this tutorial, we will learn how to create an Expression object (similar to #string, #dates, #lists), using Thymeleaf. It will check whether a number is even or odd. For this, let’s use a quick and practical example.

What Is a Thymeleaf Dialect?

A dialect allows you to add custom functionality to thymeleaf. Thus extending your ability to build and reuse templates.

Maven Dependencies

First, let’s add our Thymeleaf dependency to the pom.xml file:

XML

<dependency>
        <groupId>nz.net.ultraq.thymeleaf</groupId>
        <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

This dependency will allow us to use the standard thymeleaf dialect.

Creating Our Dialect

The creation of our dialect goes through the creation of 3 classes: Utils, Factory and Dialect.

Number Utils Class

The Utils class will contain all of our business logic. It is in this class where all of our Java code will stay.

Java

public final class NumberUtils {

    public String isEven(Integer number) {
        if (number % 2 == 0) {
            return number +" is even";
        } else {
            return number + " is not even";
        }
    }
}

Factory Class

This class is responsible for generating our utils object and will return it to the thymeleaf template engine.

Java

public class NumberExpresseionFactory implements IExpressionObjectFactory {
    private static final String TEMPORAL_EVALUATION_VARIABLE_NAME = "number";

    private static final Set<String> ALL_EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(TEMPORAL_EVALUATION_VARIABLE_NAME)));

    @Override
    public Set<String> getAllExpressionObjectNames() {
        return ALL_EXPRESSION_OBJECT_NAMES;
    }
    @Override
    public Object buildObject(
IExpressionContext context, String expressionObjectName) {
        if (
TEMPORAL_EVALUATION_VARIABLE_NAME.equals(expressionObjectName)) {
            return new NumberUtils();
        }
        return null;
    }
    @Override
    public boolean isCacheable(String expressionObjectName) {
        return true;
    }
}

#java #tutorial #web dev #spring framework #thymeleaf #expression objects

Creating an Expression Object Using Thymeleaf
2.85 GEEK