0% found this document useful (0 votes)
28 views12 pages

Spring Boot Thymeleaf Hello World Guide

This document is a tutorial on creating a Hello World web application using Spring Boot and Thymeleaf. It outlines the necessary prerequisites, project structure, dependencies, and provides code examples for the controller and view template. The tutorial concludes with instructions on running the application and testing it in a web browser.

Uploaded by

marc0000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views12 pages

Spring Boot Thymeleaf Hello World Guide

This document is a tutorial on creating a Hello World web application using Spring Boot and Thymeleaf. It outlines the necessary prerequisites, project structure, dependencies, and provides code examples for the controller and view template. The tutorial concludes with instructions on running the application and testing it in a web browser.

Uploaded by

marc0000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

HelloKoding
Guides Spring Boot JPA and Hibernate REST with Spring Security with Spring Java Data Structure Algorithm

Golang

Spring Boot Thymeleaf Tutorial with Example


Last modified @ 26 October 2020

# Spring Boot

This tutorial walks you through the steps of creating a Hello World web app example with Spring Boot
and Thymeleaf

Thymeleaf is a server-side Java template engine for both web and standalone environments

What you will build


A Spring Boot web application using Thymeleaf view template for server-side rendering (SSR) HTML
web page

The web page accepts and shows the value of a query string parameter input from the user on the HTML
web page

What you'll need


JDK 8+ or OpenJDK 8+

Maven 3+

Your favorite IDE

Init project structure

[Link] 1/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

You can create and init a new Spring Boot project by using Spring Initializr or your IDE

Following is the final project structure with all the files we would create

├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── hellokoding
│ │ └── springboot
│ │ └── view
│ │ ├── [Link]
│ │ └── [Link]
│ └── resources
│ ├── static
│ │ ├── css
│ │ │ └── [Link]
│ │ └── js
│ │ └── [Link]
│ ├── templates
│ │ └── [Link]
│ └── [Link]
└── [Link]

[Link] is the configuration file used by Maven to manage project dependencies and build process, it
is usually placed in the project root directory

Web controller classes are used for mapping user requests to Thymeleaf template files, would be created
inside src/main/java

Thymeleaf view template files would be created inside src/main/resources/templates

CSS and JavaScript files would be created inside src/main/resources/static

[Link] is a configuration file used by Spring Boot, would be created inside


src/main/resources

[Link] is a launch file for Spring Boot to start the application, would be created inside
src/main/java

Project dependencies
For a Spring Boot Thymeleaf web application, we will need the following dependencies on the [Link]
file

[Link] 2/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

spring-boot-starter-web provides all the dependencies and auto-configuration we need to


develop a web application in Spring Boot, including the Tomcat embedded servlet container

spring-boot-starter-thymeleaf provides the support for compiling Thymeleaf files

The library versions can be omitted as it will be resolved by the parent pom provided by Spring Boot

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Apart from that, we also use the spring-boot-devtools dependency to auto-trigger an application
restart or live reload in the development environment whenever Java class or static files on class-path
change, respectively. However, to leverage that, you need to configure your IDE to auto-save and auto-
compile when files are modified

In the production environment, when a Spring Boot application is launched from a jar file, the
devtools is auto disabled

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>

Create Controller
Create a Spring Boot controller file to map HTTP requests to Thymeleaf view template files

[[Link]]

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@Controller

[Link] 3/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example
public class HelloController {
@GetMapping({"/", "/hello"})
public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="Wo
[Link]("name", name);
return "hello";
}
}

The @Controller annotation indicates the annotated class is a web controller

@GetMapping maps HTTP GET request for "/" (home page) and "/hello" to the hello method

@RequestParam binds method parameter name to request query string parameter

Model is a Spring object for sharing data between handler and view template

The view template name is defined by the return statement of the handler and the
[Link] config property which defined in the below
[Link] file. So in this hello handler method, the return view is
[Link]

Create Thymeleaf View Template file


Create a simple Thymeleaf view template file to show a dynamic message to user

[[Link]]

<!DOCTYPE html>
<html lang="en" xmlns:th="[Link]
<head>
<meta charset="UTF-8">
<title th:text="'Hello, ' + ${name} + '!'"></title>
<link href="/css/[Link]" rel="stylesheet">
</head>
<body>
<h2 class="hello-title" th:text="'Hello, ' + ${name} + '!'"></h2>
<script src="/js/[Link]"></script>
</body>
</html>

The dynamic message is ${name} . It is an Java Expression Language enabling Thymeleaf files to access
the data from the model. Its value is filled by the [Link]("name", name); defined
in the above HelloController

[Link] 4/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

Static files
Create 2 simple CSS and JavaScript files inside /src/main/resources/static

The [Link] file is linked into Thymeleaf view via <link href="/css/[Link]"
rel="stylesheet">

[[Link]]

.hello-title{
color: darkgreen;
}

The [Link] file is included into Thymeleaf view via <script src="/js/[Link]">
</script>

[[Link]]

(function(){
[Link]("Hello World!");
})();

Application Configurations
Create [Link] file inside src/main/resources to configure Spring MVC
view resolver via the [Link] properties

[[Link]]

[Link]-loader-path: classpath:/templates
[Link]: .html
[Link]: false

The [Link]-loader-path property defines the path to Thymeleaf files,


the [Link] property defines the file extension we would like to use

Under the hood, Spring Boot will auto-configure Spring MVC view resolver based on the above settings

Run and Test

Create an Application class and use @SpringBootApplication annotation to launch the application

[Link] 5/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

[[Link]]

package [Link];

import [Link];
import [Link];

@SpringBootApplication
public class Application {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Run the application by typing the following command on the terminal console at the project root
directory

./mvnw clean spring-boot:run

You would see this text in the console

[Link] : Tomcat started on port(s): 8080 (http)

with context path ''

Access to [Link] on your web browser, the following response is expected

Hello, World!

Try to modify the Thymeleaf, CSS, and JavaScript files, and refresh the browser, the HTML response
would be updated accordingly thanks to the support from spring-boot-devtools

In a production environment, you may like to package and run the Spring Boot application as a single jar
file

./mvnw clean package


java -jar target/[Link]

[Link] 6/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

Conclusion
In this tutorial, we learned to create a Hello World web application in Spring Boot with Thymeleaf. The
source code is available on Github

# Spring Boot

Share to social

Twitter Facebook

Van N.
Van N. is a software engineer, creator of HelloKoding. He loves coding, blogging, and traveling. You may find him
on GitHub and LinkedIn

Comments

[Link] 7/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

17 Comments 
1 Login

G Join the discussion…

LOG IN WITH OR SIGN UP WITH DISQUS ?

Name

 11 Share Best Newest Oldest

YD Yesid Davila. − ⚑
7 years ago

Hello, I do the steps of the example and the project runs smoothly.
but when searching the path in the browser, the html view is not displayed.
instead, this message appears:

"Whitelabel Error Page


This application has no explicit mapping for / error, so you are seeing this as a fallback.
Mon Feb 05 22:41:53 VET 2018
There was an unexpected error (type = Not Found, status = 404).
No message available "

I repeat, the project runs smoothly. but it does not show the view.

4 4 Reply ⥅

Sumit Shrestha > Yesid Davila.


− ⚑
7 years ago

ya how to fix it...?? what is project structure for netbeans??

0 0 Reply ⥅

Lukas Gužauskas − ⚑
5 years ago

Hello, I do the steps of the example and the project runs smoothly.
But the browser doesn't find /css/[Link]. I get error page that htttp is not found 404

Can someone explaine me?


0 0 Reply ⥅

Сергей − ⚑
5 years ago

Please help me include header and footer in my jsp page :)

0 0 Reply ⥅

Ruan Nawê − ⚑
5 years ago

Excelent tutorial
0 0 Reply ⥅

F
Ferko − ⚑
5 years ago

Please, Coud somebody tell me, what is the meaning of [Link]?

0 0 Reply ⥅

I Ivana Milic − ⚑
5 years ago
[Link] 8/12
I
19/12/2024 16:34
5 years ago
Spring Boot Thymeleaf Tutorial with Example

Thank you!
0 0 Reply ⥅

deadxperia − ⚑
5 years ago

It doesn't work. Author please update the repository or just delete this article, it's useless until you fix it.

0 0 Reply ⥅

T test > deadxperia


− ⚑
5 years ago

Of cource you are not capable of fixing it yourself because idiot


0 0 Reply ⥅

S
starrychloe − ⚑
6 years ago

Got the exception

[Link]: Error resolving template "index", template might not exist or might
not be accessible by any of the configured Template Resolvers
0 0 Reply ⥅

G
Got Motivation − ⚑
7 years ago

You Save my time. Thank you.

0 0 Reply ⥅

T Trnal − ⚑
7 years ago

AMAZING !!!!! thank you so much :)

0 0 Reply ⥅

Mathenge − ⚑
8 years ago

Thank you very much. This really helped me.

0 0 Reply ⥅

Kevin Yang − ⚑
8 years ago

Hi,Giau [Link] I reprint your articles translated into Chinese?


0 0 Reply ⥅

Van N. Mod > Kevin Yang − ⚑


8 years ago

Sure Kevin, feel free

0 0 Reply ⥅

Avata This comment was deleted. −

WG Wael Gomaa
> Guest − ⚑
8 years ago

you can use [Link] instead (Y)

3 0 Reply ⥅

Wiktor Kalinowski − ⚑
7 years ago
[Link] 9/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

Working fine, good tutorial ;)


0 1 Reply ⥅

Search ...

[Link] 10/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

[Link] 11/12
19/12/2024 16:34 Spring Boot Thymeleaf Tutorial with Example

HelloKoding - Practical Coding Guides, Tutorials and Examples Series


Guides

Spring Boot

JPA and Hibernate

REST with Spring

Security with Spring

Java

Data Structure

Algorithm

Golang

GitHub

Facebook

Twitter

LinkedIn

© 2023 HelloKoding - Practical Coding Guides, Tutorials and Examples Series


Content on this site is available under the CC-BY-4.0 license

Paramètres concernant la confidentialité et les cookies


Géré par Google. Conforme au TCF de l'IAB. ID de CMP : 300

[Link] 12/12

Common questions

Powered by AI

Thymeleaf integrates with Spring Boot by using the 'spring-boot-starter-thymeleaf' dependency, which provides the framework for server-side rendering (SSR) of HTML pages. In a Spring Boot application, controller methods handle HTTP requests, pass model data, and specify the view name. Thymeleaf templates located in the 'templates' directory use this model data to render dynamic web pages by embedding expressions like '${name}' within HTML, which are resolved by Thymeleaf at runtime .

Spring-boot-devtools aids in the development of a Spring Boot application by allowing automatic restarts or live reloading whenever Java classes or static files change. This is useful during development for speeding up the build-test cycle. However, to take full advantage, the development environment must be configured to auto-save and auto-compile changes. This tool is automatically disabled in production environments for performance reasons .

The Model object in a Spring Boot application facilitates data sharing by acting as a container that holds attributes that are accessible in the view templates. In controller methods, you add attributes using 'model.addAttribute()' which can then be accessed in Thymeleaf templates with expression language. This allows the controller to pass dynamic content to be included in the rendered HTML .

To create a Spring Boot web application with Thymeleaf, the necessary dependencies include 'spring-boot-starter-web' for web application development, 'spring-boot-starter-thymeleaf' for Thymeleaf template support, and 'spring-boot-devtools' for enabling live reload and auto restart during development. These dependencies are added in the project's pom.xml file .

The @GetMapping annotation in a Spring Boot controller maps HTTP GET requests to specific handler methods in the controller. For example, in the 'HelloController', @GetMapping({"/", "/hello"}) is used to map requests for the home page and '/hello' to the 'hello' method, which then processes the request .

A new Spring Boot project can be initiated using Spring Initializr by selecting the project details such as Project Metadata, Dependencies, and Packaging Type through a web-based interface. This generates a pre-configured Maven project with a pom.xml containing selected dependencies, which can then be imported into an IDE for development .

The application.properties file in a Spring Boot application is used to configure various properties, such as defining the Thymeleaf view resolver. It sets properties like 'spring.thymeleaf.template-loader-path', 'spring.thymeleaf.suffix', and 'spring.thymeleaf.cache' to specify the directory and file suffix for Thymeleaf templates, as well as caching behavior .

To package a Spring Boot application into a jar file for production, you must ensure all necessary dependencies are specified in pom.xml and the main application class is correctly annotated with @SpringBootApplication. By executing 'mvn clean package', a jar file is created in the 'target' directory. This jar includes all dependencies and is executable, making it easy to deploy on server environments. Additionally, devtools are automatically disabled in the jar package for optimized performance .

If a Spring Boot application does not display the expected HTML view, potential issues include misconfiguration of the view resolver in application.properties, incorrect mapping of the controller method to the desired URL, or missing or incorrectly named Thymeleaf template files. A common error includes the "Whitelabel Error Page" indicating no mapping for a requested path or a "TemplateInputException" for an inaccessible template .

Using Thymeleaf's Java Expression Language (EL) in templates is crucial for integrating back-end logic with the front-end presentation. EL enables accessing and displaying model data as well as evaluating conditional logic directly within the HTML structure of the templates. It allows for dynamic content generation, thereby providing a versatile mechanism for constructing interactive and responsive web pages .

You might also like