What is the method of integrating Thymeleaf with Spring Boot?
- First, add the dependency for Thymeleaf in the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- Ensure that the template path for Thymeleaf is configured in the application.properties file.
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
- Create a Controller class to handle page requests and return Thymeleaf templates.
@Controller
public class MyController {
@RequestMapping("/myPage")
public String myPage(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "myPage";
}
}
- Create a Thymeleaf template file (myPage.html) and use Thymeleaf syntax to render the page within the file.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>My Page</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
- To start the Spring Boot application, go to http://localhost:8080/myPage to see the message “Hello, Thymeleaf!” displayed on the page.
By following the above steps, you can achieve the integration of Spring Boot with Thymeleaf.