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
In the following example we will use
? operator to handle nullable
Java model that was used in the above example has the following structure:
address is null, the
p tag will be empty. Without safe operators we will face a NullPointerException.
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.