Skip to content

Thymeleaf Spring integration

Thymeleaf is a modern server-side Java template engine used in web applications, particularly for Spring-based projects^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md].

Version Configuration

When integrating with Spring, specific library versions are defined in the project properties. For example, upgrading to Thymeleaf version 3 requires setting the thymeleaf.version and the corresponding layout dialect version^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md].

<properties>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>

Spring MVC auto-configuration

Spring Boot's auto-configuration for Spring MVC (WebMvcAutoConfiguration) handles the setup of resources and mappings necessary for web applications^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md].

Static Resource Locations

By default, Spring MVC looks for static resources in specific classpath locations^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md]:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/

WebJars Support

The integration includes automatic handling for WebJars. Resource handlers are registered to map requests starting with /webjars/** to dependencies located under classpath:/META-INF/resources/webjars/^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md].

Welcome Page

A WelcomePageHandlerMapping is configured to serve a welcome page (index page) by default, utilizing the static resource path pattern^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md].

Thymeleaf Syntax

The engine uses specific syntax expressions to perform standard operations within templates^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md]:

  • Variable Expressions: ${...} is used for Object-Graph Navigation Language (OGNL) expressions.
  • Selection Expressions: *{...} (often used with *{object.xxx}) selects a specific object.
  • Message Expressions: #{...} is used for internationalization.
  • Link URL Expressions: @{...} is used to define URLs.
  • Fragment Expressions: ~{...} is used to reference template fragments.
  • Attribute Modification: Attributes like th:id can be used to modify or replace standard HTML attributes.

Sources

^[600-developer-java-spring-thymeleaf-spring-thymeleaf-01.md]