Blog Image

Spring with Thymeleaf  

Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS and Text. Let's explore how to integrate Spring MVC application with Thymeleaf. Thymeleaf makes development faster than using Jsp's.

Here we will integrate Spring MVC application with Thymeleaf.

Technologies Used

  • Spring 5.0.2.RELEASE
  • Java 8
  • Thymeleaf 3.0.9.RELEASE
  • Tomcat 9

Project Structure

Maven Dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">;
    <modelVersion>4.0.0</modelVersion>
    <groupId>oracle.com</groupId>
    <artifactId>thymeleaf</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>thymeleaf Maven Webapp</name>
    <url>http://maven.apache.org</url>;
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>${javaee-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>thymeleaf</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven-compiler-plugin.version}</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <showDeprecation>true</showDeprecation>
                        <showWarnings>true</showWarnings>
                        <fork>true</fork>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <properties>
        <maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
        <javaee-api.version>6.0</javaee-api.version>
        <javax.servlet.version>3.1.0</javax.servlet.version>
    </properties>
</project>


Below is the configuration required for integrating Spring + Thymeleaf

To integrate Spring + Thymeleaf we need SpringResourceTemplateResolver, this class will identify the Thymeleaf template and mode of the Template as HTML. SpringTemplateEngine used templateResolver.

Then we need ThymeleafViewResolver to resolve logical viewName to the Thymeleaf Template. Below is the configuration for the above three classes.

<bean id="templateResolver"
        class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
    </bean>

    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <property name="viewNames" value="*.html,*.xhtml" />
    </bean>


Model object to bind the data to display in the jsp page

package com.thymeleaf.dto;

public class Account {
    protected int accountNo;
    protected String accountHolderName;
    protected String accountType;

    public Account(int accountNo, String accountHolderName, String accountType) {
        super();
        this.accountNo = accountNo;
        this.accountHolderName = accountHolderName;
        this.accountType = accountType;
    }

    public int getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(int accountNo) {
        this.accountNo = accountNo;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    public String getAccountType() {
        return accountType;
    }

    public void setAccountType(String accountType) {
        this.accountType = accountType;
    }

}

Controller for binding data to be rendered as part of Thymeleaf view

package com.thymeleaf.controller;

import java.util.ArrayList;
import java.util.List;

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

import com.thymeleaf.dto.Account;

@Controller
public class ListAccountsController {
    @RequestMapping("/accounts.htm")
    public String showAccounts(Model model) {
        List<Account> accounts = null;

        /* adding some dummy accounts to display in view */
        accounts = new ArrayList<>();
        accounts.add(new Account(1, "Susan", "savings"));
        accounts.add(new Account(2, "Brain", "current"));

        model.addAttribute("accounts", accounts);
        return "accounts.html";
    }
}

Finally let's create the Thymeleaf HTML page to render the above data.

accounts.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">;
<html xmlns:th="http://www.thymeleaf.org">;
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Accounts</title>
    </head>
    <body>
        <table th:if="${not #lists.isEmpty(accounts)}">
            <tr>
                <th>Account Holder Name</th>
                <th>Type</th>
            </tr>
            <tr th:each="account:${accounts}">
                <td th:text="${account.accountHolderName}">Account Holder Name</td>
                <td th:text="${account.accountType}">Type</td>
            </tr>
           
        </table>
    </body>
</html>


web.xml configured with DispatcherServlet

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd"; >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>


After deploying the application we can access it using http://localhost:8080/thymeleaf/accounts.htm
Refer to the example attached to this blog thymeleaf.zip

Simple Attributes

model.addAttribute("message", "Welcome to Thymeleaf");

<span th:text="${message}">This is a message</span>


Conditional Statements

  • If and Unless


<td>
 <span th:if="${account.accountType} == 'savings'" th:text="ATM withdraw only"></span>
    <span th:unless="${account.accountType} == 'savings'" th:text="ATM and Check withdraw">
</td>

  • Switch and case

  

  <td th:switch="${account.accountType}">
          <span case="savings" th:text="ATM withdraw only"/>
          <span case="current" th:text="ATM and check withdraw"/>
       </td>
  





About author

User Image
Sriman

A software developer on JDK and JEE platform. I am passionate about Java technology and always an explorer and learner in new technologies in Java. I have experience on Open Source technologies like Struts, Spring, Jsf etc.. and even strong knowledge on Integration/Distributed world like Ejb, Web Services and Restful Services.

3

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      RAMBALAK4101
      27 Days ago

    thank u for writing for this content . It is so useful content for us.

  • author image
    by:
      Suneel
      29 Days ago

    Thanque for writing this blog it is use full for me.

  • author image
    by:
      Pratish
      21-12-2017 11:47:06 AM

    helpful content,Thank u ! Plz give some info about how to add static resources(css,js,images...) with thymeleaf into project.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.