DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Spring MVC Thymeleaf Utilities Tutorial

Table of Contents

  1. string-utilities
  2. date-utilities
  3. number-utilities
  4. collection-utilities
  5. object-utilities
  6. conditional-utilities
  7. aggregate-examples

String Utilities

Basic String Operations

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>String Utilities</title>
</head>
<body>
    <h1>String Utility Examples</h1>

    <!-- Basic string operations -->
    <div th:with="text='Hello Thymeleaf'">
        <p>Original: <span th:text="${text}"></span></p>
        <p>Length: <span th:text="${#strings.length(text)}"></span></p>
        <p>Uppercase: <span th:text="${#strings.toUpperCase(text)}"></span></p>
        <p>Lowercase: <span th:text="${#strings.toLowerCase(text)}"></span></p>
        <p>Substring (0-5): <span th:text="${#strings.substring(text, 0, 5)}"></span></p>
        <p>Replace: <span th:text="${#strings.replace(text, 'Thymeleaf', 'World')}"></span></p>
    </div>

    <!-- String checks -->
    <div th:with="emptyString='', nullString=null, text='Hello'">
        <p>Is empty: <span th:text="${#strings.isEmpty(emptyString)}"></span></p>
        <p>Is null or empty: <span th:text="${#strings.isEmpty(nullString)}"></span></p>
        <p>Contains 'ell': <span th:text="${#strings.contains(text, 'ell')}"></span></p>
        <p>Starts with 'He': <span th:text="${#strings.startsWith(text, 'He')}"></span></p>
        <p>Ends with 'lo': <span th:text="${#strings.endsWith(text, 'lo')}"></span></p>
    </div>

    <!-- String formatting -->
    <div>
        <p>Concatenation: <span th:text="${'Hello ' + 'World'}"></span></p>
        <p>String literal: <span th:text="|Hello ${text}|"></span></p>
    </div>

    <!-- Escape/Unescape -->
    <div th:with="htmlContent='<b>Bold Text</b>'">
        <p>Escaped: <span th:text="${htmlContent}"></span></p>
        <p>Unescaped: <span th:utext="${htmlContent}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Controller for String Examples

@GetMapping("/string-utils")
public String stringUtils(Model model) {
    model.addAttribute("message", "Hello Thymeleaf Utilities!");
    model.addAttribute("htmlContent", "<div class='alert'>Important <b>message</b></div>");
    return "string-utils";
}
Enter fullscreen mode Exit fullscreen mode

Date Utilities

Date Operations

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Date Utilities</title>
</head>
<body>
    <h1>Date Utility Examples</h1>

    <!-- Current date/time -->
    <div>
        <p>Now: <span th:text="${#temporals.createNow()}"></span></p>
        <p>Today: <span th:text="${#temporals.createToday()}"></span></p>
    </div>

    <!-- Date formatting -->
    <div th:with="currentDate=${#temporals.createNow()}">
        <p>Default format: <span th:text="${currentDate}"></span></p>
        <p>Formatted date: <span th:text="${#temporals.format(currentDate, 'yyyy-MM-dd')}"></span></p>
        <p>Formatted datetime: <span th:text="${#temporals.format(currentDate, 'yyyy-MM-dd HH:mm:ss')}"></span></p>
        <p>Day of month: <span th:text="${#temporals.day(currentDate)}"></span></p>
        <p>Month: <span th:text="${#temporals.month(currentDate)}"></span></p>
        <p>Month name: <span th:text="${#temporals.monthName(currentDate)}"></span></p>
        <p>Year: <span th:text="${#temporals.year(currentDate)}"></span></p>
        <p>Day of week: <span th:text="${#temporals.dayOfWeek(currentDate)}"></span></p>
        <p>Day of week name: <span th:text="${#temporals.dayOfWeekName(currentDate)}"></span></p>
    </div>

    <!-- Date arithmetic -->
    <div th:with="currentDate=${#temporals.createNow()}">
        <p>Plus 1 day: <span th:text="${#temporals.addDays(currentDate, 1)}"></span></p>
        <p>Minus 1 week: <span th:text="${#temporals.addWeeks(currentDate, -1)}"></span></p>
        <p>Plus 1 month: <span th:text="${#temporals.addMonths(currentDate, 1)}"></span></p>
    </div>

    <!-- Date comparison -->
    <div th:with="today=${#temporals.createToday()}, 
                 tomorrow=${#temporals.addDays(#temporals.createToday(), 1)}">
        <p>Today before tomorrow: <span th:text="${#temporals.before(today, tomorrow)}"></span></p>
        <p>Tomorrow after today: <span th:text="${#temporals.after(tomorrow, today)}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Controller for Date Examples

@GetMapping("/date-utils")
public String dateUtils(Model model) {
    model.addAttribute("birthDate", LocalDate.of(1990, 5, 15));
    model.addAttribute("appointment", LocalDateTime.of(2023, 12, 25, 14, 30));
    return "date-utils";
}
Enter fullscreen mode Exit fullscreen mode

Number Utilities

Number Formatting and Operations

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Number Utilities</title>
</head>
<body>
    <h1>Number Utility Examples</h1>

    <!-- Basic number operations -->
    <div th:with="number=12345.6789, quantity=42">
        <p>Original number: <span th:text="${number}"></span></p>
        <p>Formatted number: <span th:text="${#numbers.formatDecimal(number, 1, 2)}"></span></p>
        <p>Integer part: <span th:text="${#numbers.integerPart(number)}"></span></p>
        <p>Fractional part: <span th:text="${#numbers.fractionalPart(number)}"></span></p>
        <p>Format currency: <span th:text="${#numbers.formatCurrency(number)}"></span></p>
        <p>Format percent: <span th:text="${#numbers.formatPercent(number/100, 1, 2)}"></span></p>

        <!-- Sequence generation -->
        <p>Sequence: 
            <span th:each="i : ${#numbers.sequence(1, 5)}" th:text="${i} + ' '"></span>
        </p>
    </div>

    <!-- Array utilities -->
    <div th:with="numbers=${#arrays.toIntegerArray({1, 2, 3, 4, 5})}">
        <p>Array length: <span th:text="${#arrays.length(numbers)}"></span></p>
        <p>Array contains 3: <span th:text="${#arrays.contains(numbers, 3)}"></span></p>
    </div>

    <!-- Math operations -->
    <div th:with="a=10, b=3">
        <p>a + b = <span th:text="${a + b}"></span></p>
        <p>a - b = <span th:text="${a - b}"></span></p>
        <p>a * b = <span th:text="${a * b}"></span></p>
        <p>a / b = <span th:text="${a / b}"></span></p>
        <p>a % b = <span th:text="${a % b}"></span></p>
        <p>Min: <span th:text="${#numbers.min(a, b)}"></span></p>
        <p>Max: <span th:text="${#numbers.max(a, b)}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Collection Utilities

Collection Operations

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Collection Utilities</title>
</head>
<body>
    <h1>Collection Utility Examples</h1>

    <!-- List operations -->
    <div th:with="fruits=${#lists.toList({'apple', 'banana', 'orange', 'grape'})}">
        <p>List size: <span th:text="${#lists.size(fruits)}"></span></p>
        <p>Is empty: <span th:text="${#lists.isEmpty(fruits)}"></span></p>
        <p>Contains 'apple': <span th:text="${#lists.contains(fruits, 'apple')}"></span></p>
        <p>First element: <span th:text="${#lists.first(fruits)}"></span></p>
        <p>Last element: <span th:text="${#lists.last(fruits)}"></span></p>
        <p>Sorted: <span th:text="${#lists.sort(fruits)}"></span></p>
    </div>

    <!-- Set operations -->
    <div th:with="uniqueNumbers=${#sets.toSet({1, 2, 2, 3, 3, 3})}">
        <p>Set elements: 
            <span th:each="num : ${uniqueNumbers}" th:text="${num} + ' '"></span>
        </p>
        <p>Set size: <span th:text="${#sets.size(uniqueNumbers)}"></span></p>
    </div>

    <!-- Map operations -->
    <div th:with="userMap=${#maps.toMap({'name': 'John', 'age': 30, 'city': 'New York'})}">
        <p>Map size: <span th:text="${#maps.size(userMap)}"></span></p>
        <p>Contains key 'name': <span th:text="${#maps.containsKey(userMap, 'name')}"></span></p>
        <p>Contains value 30: <span th:text="${#maps.containsValue(userMap, 30)}"></span></p>
        <p>Get value for 'city': <span th:text="${#maps.get(userMap, 'city')}"></span></p>
    </div>

    <!-- Aggregate functions -->
    <div th:with="numbers=${#arrays.toIntegerArray({10, 20, 30, 40, 50})}">
        <p>Sum: <span th:text="${#aggregates.sum(numbers)}"></span></p>
        <p>Average: <span th:text="${#aggregates.avg(numbers)}"></span></p>
        <p>Min: <span th:text="${#aggregates.min(numbers)}"></span></p>
        <p>Max: <span th:text="${#aggregates.max(numbers)}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Object Utilities

Object Operations

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Object Utilities</title>
</head>
<body>
    <h1>Object Utility Examples</h1>

    <!-- Null checks -->
    <div th:with="nullVar=null, emptyString='', someValue='Hello'">
        <p>Is null: <span th:text="${#objects.isNull(nullVar)}"></span></p>
        <p>Is not null: <span th:text="${#objects.nullSafe(someValue, 'Default')}"></span></p>
        <p>Null-safe with default: <span th:text="${#objects.nullSafe(nullVar, 'Default Value')}"></span></p>
    </div>

    <!-- Array utilities -->
    <div th:with="array=${#arrays.toArray({1, 2, 3, 4, 5})}">
        <p>Array length: <span th:text="${#arrays.length(array)}"></span></p>
        <p>Array contains 3: <span th:text="${#arrays.contains(array, 3)}"></span></p>
        <p>First element: <span th:text="${#arrays.first(array)}"></span></p>
        <p>Last element: <span th:text="${#arrays.last(array)}"></span></p>
    </div>

    <!-- Boolean utilities -->
    <div th:with="isActive=true, hasPermission=false">
        <p>Is active: <span th:text="${isActive} ? 'Yes' : 'No'"></span></p>
        <p>Has permission: <span th:text="${hasPermission} ? 'Yes' : 'No'"></span></p>
        <p>Logical AND: <span th:text="${isActive and hasPermission}"></span></p>
        <p>Logical OR: <span th:text="${isActive or hasPermission}"></span></p>
        <p>Logical NOT: <span th:text="${not hasPermission}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Conditional Utilities

Advanced Conditionals

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Conditional Utilities</title>
</head>
<body>
    <h1>Conditional Utility Examples</h1>

    <!-- Elvis operator (default values) -->
    <div th:with="name=null, age=25">
        <p>Name: <span th:text="${name} ?: 'Unknown'"></span></p>
        <p>Age: <span th:text="${age} ?: 'Not specified'"></span></p>
    </div>

    <!-- Ternary operator -->
    <div th:with="score=85">
        <p>Grade: <span th:text="${score >= 90} ? 'A' : (${score >= 80} ? 'B' : 'C')"></span></p>
        <p>Status: <span th:text="${score >= 70} ? 'Pass' : 'Fail'"></span></p>
    </div>

    <!-- Multiple conditions -->
    <div th:with="userRole='admin', isActive=true">
        <p th:if="${userRole == 'admin' and isActive}">Admin access granted</p>
        <p th:unless="${userRole == 'admin' and isActive}">Access denied</p>

        <div th:switch="${userRole}">
            <p th:case="'admin'">Administrator privileges</p>
            <p th:case="'user'">User privileges</p>
            <p th:case="'guest'">Guest privileges</p>
            <p th:case="*">Unknown role</p>
        </div>
    </div>

    <!-- Collection conditionals -->
    <div th:with="emptyList=${#lists.toList({})}, 
                 populatedList=${#lists.toList({1, 2, 3})}">
        <p>Empty list: <span th:text="${#lists.isEmpty(emptyList)}"></span></p>
        <p>Populated list: <span th:text="${not #lists.isEmpty(populatedList)}"></span></p>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Aggregate Examples

Complete Utility Example

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>All Utilities Example</title>
    <style>
        .example { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
        .result { color: #28a745; font-weight: bold; }
    </style>
</head>
<body>
    <h1>Comprehensive Thymeleaf Utilities Example</h1>

    <!-- String Example -->
    <div class="example">
        <h2>String Utilities</h2>
        <div th:with="text='Hello Thymeleaf Utilities'">
            <p>Original: <span class="result" th:text="${text}"></span></p>
            <p>Uppercase: <span class="result" th:text="${#strings.toUpperCase(text)}"></span></p>
            <p>Substring: <span class="result" th:text="${#strings.substring(text, 0, 5)}"></span></p>
        </div>
    </div>

    <!-- Date Example -->
    <div class="example">
        <h2>Date Utilities</h2>
        <div th:with="now=${#temporals.createNow()}">
            <p>Current: <span class="result" th:text="${now}"></span></p>
            <p>Formatted: <span class="result" th:text="${#temporals.format(now, 'yyyy-MM-dd HH:mm')}"></span></p>
            <p>+1 Week: <span class="result" th:text="${#temporals.addWeeks(now, 1)}"></span></p>
        </div>
    </div>

    <!-- Number Example -->
    <div class="example">
        <h2>Number Utilities</h2>
        <div th:with="price=1234.5678">
            <p>Original: <span class="result" th:text="${price}"></span></p>
            <p>Currency: <span class="result" th:text="${#numbers.formatCurrency(price)}"></span></p>
            <p>Rounded: <span class="result" th:text="${#numbers.formatDecimal(price, 1, 2)}"></span></p>
        </div>
    </div>

    <!-- Collection Example -->
    <div class="example">
        <h2>Collection Utilities</h2>
        <div th:with="items=${#lists.toList({'Apple', 'Banana', 'Orange'})}">
            <p>Items: <span class="result" th:text="${items}"></span></p>
            <p>Count: <span class="result" th:text="${#lists.size(items)}"></span></p>
            <p>Sorted: <span class="result" th:text="${#lists.sort(items)}"></span></p>
        </div>
    </div>

    <!-- Conditional Example -->
    <div class="example">
        <h2>Conditional Utilities</h2>
        <div th:with="userRole='admin', items=${#lists.toList({'Apple'})}">
            <p>Is Admin: <span class="result" th:text="${userRole == 'admin'} ? 'Yes' : 'No'"></span></p>
            <p>Has Items: <span class="result" th:text="${not #lists.isEmpty(items)} ? 'Yes' : 'No'"></span></p>
        </div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Controller for All Examples

@GetMapping("/all-utils")
public String allUtils(Model model) {
    // String examples
    model.addAttribute("message", "Hello Thymeleaf!");

    // Date examples
    model.addAttribute("currentDate", LocalDate.now());
    model.addAttribute("currentDateTime", LocalDateTime.now());

    // Number examples
    model.addAttribute("price", 1234.5678);
    model.addAttribute("quantity", 42);

    // Collection examples
    List<String> fruits = Arrays.asList("Apple", "Banana", "Orange", "Grape");
    model.addAttribute("fruits", fruits);

    // Object examples
    model.addAttribute("user", Map.of("name", "John", "age", 30, "active", true));

    return "all-utils";
}
Enter fullscreen mode Exit fullscreen mode

Key Utility Classes Summary

Utility Class Purpose Common Methods
#strings String manipulation length(), toUpperCase(), substring(), contains(), isEmpty()
#temporals Date/time operations format(), createNow(), day(), month(), year(), addDays()
#numbers Number formatting formatDecimal(), formatCurrency(), integerPart(), sequence()
#lists List operations size(), isEmpty(), contains(), sort(), first(), last()
#arrays Array operations length(), contains(), toArray(), toIntegerArray()
#sets Set operations size(), contains(), toSet()
#maps Map operations size(), containsKey(), containsValue(), get()
#objects Object utilities isNull(), nullSafe()
#aggregates Collection aggregation sum(), avg(), min(), max()

Top comments (0)