SpringBoot + Thymeleaf 連携:簡単設定と実装方法
- 最初に、pom.xmlファイルにThymeleafの依存関係を追加してください。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- application.propertiesファイルにThymeleafのテンプレートパスを設定することを確認してください。
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
- Controllerクラスを作成して、ページリクエストを処理し、Thymeleafテンプレートを返すようにします。
@Controller
public class MyController {
@RequestMapping("/myPage")
public String myPage(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "myPage";
}
}
- Thymeleafの構文を使用して、Thymeleafテンプレートファイル(myPage.html)を作成し、ページをレンダリングします。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>My Page</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
- Spring Bootアプリケーションを起動し、http://localhost:8080/myPageにアクセスすると、「Hello, Thymeleaf!」というメッセージが表示されます。
これらの手順に従うことで、Spring BootとThymeleafの統合機能を実現することができます。