Thymeleaf Array Example - Array Index, Array Iteration

In this quick tutorial, we're going to see how we can use Arrays in Thymeleaf. For easy setup, we're going to use a spring-boot initializer to bootstrap our application.
Learn Thymeleaf at

Maven Dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">
        <relativePath />
        <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot Thymeleaf and Hibernate </description>





The Controller

For simplicity, let's use a controller with only one method which handles GET requests.
package net.javaguides.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

public class DemoController {

    public String arraysDemo(Model model) {
        String[] planets = {
        model.addAttribute("planets", planets);
        return "array-demo";

The View

In the view page, we're going to access the array planets by the name we pass it with (planets ) from our controller above.
The below Thymeleaf template demonstrates:
  1. Getting the length of the array
  2. Accessing the value of each element of the array planets by its index
  3. Iterate over the elements the array sequentially
<!DOCTYPE html>

    <meta charset="ISO-8859-1">
    <title>Insert title here</title>


    <!-- Print the length of the array -->
        Print the length of the array - <span th:text="${planets.length}"></span>

    <!-- access the value of each element of the array continents by its index -->
        <li th:text="${planets[0]}"></li>
        <li th:text="${planets[1]}"></li>
        <li th:text="${planets[2]}"></li>
        <li th:text="${planets[3]}"></li>
        <li th:text="${planets[4]}"></li>
        <li th:text="${planets[5]}"></li>
        <li th:text="${planets[6]}"></li>

    <!-- iterate over the elements the array sequentially -->

    <ul th:each="planet : ${planets}">
        <li th:text="${planet}"></li>




Hit "http://localhost:8080/arraysDemo" link in the browser will display below web page:

Related Thymeleaf Tutorials and Examples

  1. Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
  2. Thymeleaf Example with Spring Boot
  3. How to Add CSS and JS to Thymeleaf
  4. Add Bootstrap CSS to Thymeleaf
  5. How to handle null values in Thymeleaf?
  6. How to Loop a List by Index in Thymeleaf
  7. Thymeleaf Array Example - Array Index, Array Iteration
  8. Thymeleaf Enums Example
  9. Thymeleaf If Else Condition Example
  10. Thymeleaf Switch Case Example

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course