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.
A dialect allows you to add custom functionality to thymeleaf. Thus extending your ability to build and reuse templates.
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.
The creation of our dialect goes through the creation of 3 classes: Utils, Factory and Dialect.
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";
}
}
}
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