How to handle null values in Thymeleaf?

January 04, 2020 No comments Thymeleaf null values NullPointerException

1. Introduction

In this article, we will describe how to avoid NullPointerExceptions during the rendering process of the Thymeleaf template. We will show the simple method to handle unexpected null values.

2. Safe navigation operator - ?

The Safe Navigation operator (?) is used to avoid an unexpected NullPointerExceptions. Originally it was presented in the Groovy language and adapted in many other modern languages. Typically when we have a reference to an object we wanted to verify if it is null or not, before accessing any properties or methods of that object. The save navigation operator will simply return null instead of throwing a NullPointerException. We can use this operator in Thymeleaf templates to get rid of null checking conditions using th:if attributes.

In the following example we will use ? operator to handle nullable address object:

<p th:text="${customer?.address?.city}">City</p>

Java model that was used in the above example has the following structure:

class Customer {
    private String firstName;
    private String lastName;
    private Address address;

    // setters and getters
}
class Address { 
    private String city;
    private String country;
    private String street;
    private String zipCode;

    // setters and getters
}

When customer or address is null, the p tag will be empty. Without safe operators we will face a NullPointerException.

3. Conclusion

This article raises an important topic of avoiding NullPointerExceptions in Thymeleaf templates during the rendering process. With Safe navigation operator we are prepared for nullable objects that could break the whole result output.

{{ message }}

{{ 'Comments are closed.' | trans }}