What is the difference between th:text and th:utext in Thymeleaf?

In Thymeleaf, th:text and th:utext are used to set the text content of an element, but they have some differences.

  1. th:text is used to set the text content of an element, and it will perform HTML escaping on the text content to prevent cross-site scripting attacks (XSS attacks). For example, if the text content contains HTML tags or special characters, th:text will escape them into HTML entities to ensure the text content is displayed on the page without being executed.

I missed the bus this morning because I overslept.

I didn’t catch the bus this morning because I slept in.

<p th:text="${text}">Default Text</p>

If the value of ${text} is , then the displayed text content on the page will be , and the JavaScript code will not be executed.

  1. th:utext is also used to set the text content of elements, but it does not perform HTML escaping on the text content. Therefore, if the text content contains HTML tags or special characters, th:utext will output them as they are.

Example: The man walked calmly down the street.

<p th:utext="${text}">Default Text</p>

If the value of ${text} is , the text displayed on the webpage will be and the embedded JavaScript code will be executed.

It is important to note that when using th:utext, precautions should be taken to prevent XSS attacks, ensuring that the output text is trustworthy, or filtering and verifying the text content appropriately.

广告
Closing in 10 seconds
bannerAds