Spring Boot是一个快速开发框架,它可以帮助开发者快速构建独立的、生产级的基于Spring的应用。Thymeleaf是一个现代的服务器端Java模板引擎,特别适合于Web应用程序。本文将详细介绍如何将Spring Boot与Thymeleaf整合,并创建一个简单的Web应用。
环境准备
工具准备
- JDK 8 及以上
- Maven 或 Gradle
- IDE(如 IntelliJ IDEA 或 Eclipse)
创建Spring Boot项目
可以通过Spring Initializr快速生成项目
- 选择项目类型为 Maven 或 Gradle。
- 选择 Java 版本。
- 添加依赖:Spring Web、Thymeleaf
生成项目后,我们可以下载并解压,然后在IDEA中导入打开项目。
编写代码
主应用类
在com.example.mythymeleafapp包中,创建主应用类MyThymeleafApp.java,如下所示。
package com.example.mythymeleafapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyThymeleafApp {
public static void main(String[] args) {
SpringApplication.run(MyThymeleafApp.class, args);
}
}
创建控制器
在同一包下创建一个控制器 HomeController.java
package com.example.mythymeleafapp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "欢迎来到 Thymeleaf 与 Spring Boot 的整合示例!");
return "index"; // 返回 templates/index.html
}
}
创建Thymeleaf模板
在src/main/resources/templates目录下创建index.html文件,内容如下所示。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf 示例</title>
</head>
<body>
<h1 th:text="${message}">默认欢迎信息</h1>
</body>
</html>
配置文件
在application.properties配置文件中,可以配置应用的一些属性,如下所示。
spring.thymeleaf.cache=false # 开发时禁用缓存,方便调试
然后在IDEA中运行MyThymeleafApp类。打开浏览器并访问http://localhost:8080,就应该能看到欢迎信息。
进阶功能
当然我们也可以在项目中添加一些多路由配置,如下所示。、
添加更多路由
在HomeController中添加更多的路由
@GetMapping("/about")
public String about(Model model) {
model.addAttribute("info", "这是关于页面的内容。");
return "about"; // 返回 templates/about.html
}
创建about.html模板,内容如下所示。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>关于页面</title>
</head>
<body>
<h1>关于页面</h1>
<p th:text="${info}">关于信息</p>
<a href="/">返回首页</a>
</body>
</html>
使用表单
当然也可以用Thymeleaf来处理填报表单操作,如下所示,在index.html中添加表单。
<form action="#" th:action="@{/submit}" method="post">
<input type="text" name="name" placeholder="输入姓名" />
<button type="submit">提交</button>
</form>
然后再对应的控制器中处理对应的提交的表单。
@PostMapping("/submit")
public String submitForm(@RequestParam String name, Model model) {
model.addAttribute("message", "欢迎, " + name + "!");
return "index";
}
总结
通过上面的介绍,我们已经介绍了如何使用Spring Boot和Thymeleaf创建一个简单的Web应用。当然有兴趣的读者可以继续扩展这个项目,添加更多的功能和页面。同时Thymeleaf提供了丰富的功能,可以轻松实现动态页面生成和表单处理。如果遇到什么问题也可以在评论区留言,我们一起讨论实现。