引言
在Spring Boot中集成Thymeleaf作为模板引擎是一个相对简单的过程。Thymeleaf是一个适用于Java和Java EE平台的服务器端模板引擎,它能够处理HTML、XML、JavaScript、CSS甚至纯文本。
以下是将Thymeleaf集成到Spring Boot项目中的步骤:
一、 添加依赖
在项目的pom.xml文件中添加Thymeleaf的依赖:
<dependencies>
<!-- 其他依赖 -->
<!-- Thymeleaf的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
二、配置Thymeleaf
1. 方式一:通过 @Configuration 配置
// 使用@Configuration注解来声明这个类是一个Spring配置类,用于定义Thymeleaf模板引擎的Beans。
@Configuration
public class ThymeleafConfig {
// 使用@Bean注解来声明一个方法,该方法将返回一个对象,该对象将被注册为Spring应用上下文中的一个Bean。
// 这里我们定义一个SpringResourceTemplateResolver的Bean,用于配置Thymeleaf模板解析器。
@Bean
public SpringResourceTemplateResolver templateResolver() {
// 创建一个SpringResourceTemplateResolver对象
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
// 设置模板文件的前缀路径,即模板文件存放的目录
#templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setPrefix("templates/");
// 设置模板文件的后缀
templateResolver.setSuffix(".html");
// 设置模板的模式为HTML
templateResolver.setTemplateMode(TemplateMode.HTML);
// 设置模板文件的字符编码
templateResolver.setCharacterEncoding("UTF-8");
// 返回配置好的模板解析器
return templateResolver;
}
// 定义一个SpringTemplateEngine的Bean,它是Thymeleaf的核心,用于渲染模板。
@Bean
public TemplateEngine templateEngine() {
// 创建一个SpringTemplateEngine对象
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// 将之前定义的模板解析器注入到模板引擎中
templateEngine.setTemplateResolver(templateResolver());
// 返回配置好的模板引擎
return templateEngine;
}
}
2. 方式二:application.yml 配置
spring:
application:
name: springdemo
# Thymeleaf配置
thymeleaf:
# 是否启用模板缓存
cache: false
# 检查模板位置是否存在
check-template-location: true
# Content-Type值
#content-type: text/html
# 启用MVC Thymeleaf视图解析
enabled: true
# 模板编码
encoding: UTF-8
# 应用于模板的模板模式。也见StandardTemplateModeHandlers
mode: HTML5
# 在构建URL时添加到视图名称前的前缀,默认值为 classpath:/templates/
prefix: classpath:/templates/
# 在构建URL时添加到视图名称后的后缀
suffix: .html
# 模板解析器在链中的顺序(如果不设置,则使用默认值)
template-resolver-order: 1 # 默认为最低优先级
# 资源文件配置
web:
resources:
static-locations: classpath:/static/ # 指定静态资源文件夹路径
三、创建Thymeleaf模板
在src/main/resources目录下创建一个templates文件夹,并在其中添加Thymeleaf模板文件。例如,创建一个myindex.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
</head>
<body>
<h1 th:text="${message}">Welcome to our website!</h1>
</body>
</html>
注意: <html> 引入
xmlns:th="http://www.thymeleaf.org"
四、Controller 中使用模板
创建一个 Controller,使用 Thymeleaf 模板渲染视图:
@Controller
public class HomeController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello Thymeleaf!");
return "myindex"; // 返回模板文件的名称(不包括后缀)
}
}
五、运行应用
运行Spring Boot应用,并通过浏览器访问 http://localhost:8080/
六. 部署注意事项
在生产环境中,建议启用模板缓存以提高性能。
通过以上步骤,可以将Thymeleaf集成到Spring Boot项目中,并利用它提供的强大的表达式语言和自然模板语法来创建动态网页。