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”