0% found this document useful (0 votes)
18 views

Spring Boot With Thymeleaf and HTML

Uploaded by

Dheeraj Verma
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)
18 views

Spring Boot With Thymeleaf and HTML

Uploaded by

Dheeraj Verma
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
You are on page 1/ 2

Here's a comprehensive guide to using Spring Boot with Thymeleaf and HTML:

1. Project Setup:

● Spring Initializr: Create a new Spring Boot project using https://start.spring.io.


● Dependencies: Include the following dependencies:
○ Spring Web
○ Thymeleaf

2. Controller:

● Define controller classes: Use the @Controller annotation.


● Map URL patterns: Use the @RequestMapping annotation to map methods to
specific URLs.
● Return model and view name: Return a String representing the view name,
optionally along with a Model object containing data for the view.

Example:

Java:
@Controller
public class HomeController {

@RequestMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring Boot with
Thymeleaf!");
return "home"; // View name
}
}

3. Thymeleaf Templates:

● Location: Place HTML templates in the resources/templates directory.


● Syntax: Use Thymeleaf's natural templating syntax for dynamic content:
○ Variable expressions: th:text="${message}""
○ Conditionals: th:if
○ Loops: th:each
○ Links: th:href
○ Forms: th:action, th:field, th:value

Example (home.html):

HTML:
<!DOCTYPE html>

“This is written by Bard AI”


<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>

4. Running the Application:

● Start the Spring Boot application using mvn spring-boot:run or your IDE's run feature.
● Access the application in a web browser (e.g., http://localhost:8080).

Key Points:

● No configuration: Spring Boot automatically configures Thymeleaf.


● Template location: By default, templates are located in resources/templates.
● Namespaces: Use xmlns:th="http://www.thymeleaf.org" for Thymeleaf attributes.
● Natural templating: Thymeleaf templates are valid HTML even without processing.
● Spring integration: Thymeleaf works seamlessly with Spring's model and data
binding.

Additional Features:

● Fragments: Create reusable template parts for modularity.


● Layouts: Define common page structures for consistent layout.
● Internationalization: Support multiple languages with ease.

“This is written by Bard AI”

You might also like