Spring Boot集成Thymeleaf模板引擎技术指南 您所在的位置:网站首页 springboot模板引擎哪个好 Spring Boot集成Thymeleaf模板引擎技术指南

Spring Boot集成Thymeleaf模板引擎技术指南

2024-06-02 05:02| 来源: 网络整理| 查看: 265

一. 添加依赖

在Spring Boot项目中集成Thymeleaf模板引擎,首要步骤是添加Thymeleaf的依赖。Spring Boot通过起步器(Starter)简化了这一过程,使得开发者只需要在项目的构建脚本中加入相应的依赖声明即可。下面分别展示Maven和Gradle两种构建工具的依赖添加方式,并提供详细讲解。

Maven依赖添加示例

在Maven项目的pom.xml文件中,你需要包含spring-boot-starter-thymeleaf依赖。这个起步器会自动引入Thymeleaf及其所需的依赖库,还包括了Spring Boot对Thymeleaf的自动配置。

org.springframework.boot spring-boot-starter-thymeleaf

Gradle依赖添加示例

如果你的项目使用的是Gradle作为构建工具,则在build.gradle文件的dependencies块中添加如下依赖:

dependencies { implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // 其他依赖 }

详细讲解

起步器(Starter)概念:Spring Boot的起步器是一组方便的依赖描述符,它包含了启动和运行特定类型应用所需的所有依赖项。spring-boot-starter-thymeleaf就是这样的一个起步器,它包含了Thymeleaf模板引擎的核心库以及Spring Boot提供的自动配置支持。自动配置:Spring Boot对Thymeleaf进行了自动配置,这意味着在大多数情况下,你无需手动配置Thymeleaf。默认情况下,Thymeleaf模板文件会被从src/main/resources/templates目录下查找,且配置了合理的缓存策略、模板前缀和后缀等,以适应大多数应用场景。模板文件位置:Thymeleaf模板文件应放置在src/main/resources/templates目录下。Spring Boot默认会从这个目录下加载模板文件,文件名(不包括.html后缀)通常对应于控制器方法返回的视图名称。配置覆盖:尽管自动配置能满足大多数需求,但你仍然可以通过在application.properties或application.yml中添加配置项来覆盖默认设置。例如,调整模板的前缀、后缀,开启或关闭缓存等。

二. 配置Thymeleaf

在Spring Boot中配置Thymeleaf主要涉及修改application.properties或application.yml文件中的相关设置。Thymeleaf的自动配置已经很完善,但根据项目需求,你可能需要对默认配置进行一些调整。以下是一些常用的配置项及示例:

1. 关闭缓存

在开发阶段,关闭Thymeleaf的模板缓存可以让你立即看到模板更改的效果,而不需要重启应用。application.properties

spring.thymeleaf.cache=false

application.yml

spring: thymeleaf: cache: false

2. 设置模板目录

虽然默认模板目录是src/main/resources/templates,但你可以根据需要更改。application.properties

spring.thymeleaf.prefix=classpath:/custom_templates/

application.yml

spring: thymeleaf: prefix: classpath:/custom_templates/

3. 设置模板后缀

默认情况下,模板文件的后缀是.html,但你可以自定义。application.properties

spring.thymeleaf.suffix=.tmpl

application.yml

spring: thymeleaf: suffix: .tmpl

4. 模板模式

指定模板解析模式,如HTML5。application.properties

spring.thymeleaf.mode=HTML5

application.yml

spring: thymeleaf: mode: HTML5

5. 字符编码

确保模板文件的字符编码正确设置,UTF-8是最常见的选择。application.properties

spring.thymeleaf.encoding=UTF-8

application.yml

spring: thymeleaf: encoding: UTF-8

6. 开启模板引擎的SpringEL表达式

默认情况下,Thymeleaf会启用SpringEL表达式,但你可以通过以下设置来控制。application.properties

spring.thymeleaf.spring-el-allowed=true

application.yml

spring: thymeleaf: spring-el-allowed: true

详细讲解

cache: 控制模板是否被缓存。开发时关闭可以加快调试速度,生产环境则应开启以优化性能。prefix 和 suffix: 分别定义模板文件的路径前缀和文件后缀,这对于组织模板文件或使用非标准文件扩展名很有用。mode: 设定模板引擎解析模板的模式,如HTML5、XML等,影响模板的解析行为。encoding: 确保模板文件的字符编码与应用的字符编码一致,避免乱码问题。spring-el-allowed: 控制是否允许使用Spring Expression Language (SpEL) 表达式,一般应保持为true以利用Spring Boot和Thymeleaf的集成优势。

三. 创建模板文件

在Spring Boot项目中,创建Thymeleaf模板文件是实现动态页面渲染的关键步骤。模板文件通常位于src/main/resources/templates目录下,使用Thymeleaf的特定语法来插入动态数据。下面是一个简单的示例,展示如何创建一个Thymeleaf模板文件并结合Spring Boot控制器使用它。

1. 创建模板文件 假设我们要创建一个展示用户信息的页面,首先在src/main/resources/templates目录下创建一个名为user.html的文件,内容如下:

User Profile User Profile

Name:

Email:

Age:

No user data available.

2. Thymeleaf语法说明

xmlns:th: 声明Thymeleaf命名空间,使Thymeleaf表达式生效。th:text: 将元素内的文本替换为表达式计算的结果。例如,${user.name}会显示User对象的name属性。th:if: 根据表达式的布尔值决定元素是否渲染。如果user不为null,则显示用户信息;否则,显示“无用户数据可用”。

 

3. 创建控制器 接下来,在Spring Boot应用中创建一个控制器来处理请求并传递数据给模板。在你的Java控制器类中添加如下代码:

import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class UserController { @GetMapping("/user") public String showUserProfile(@RequestParam(value = "id", defaultValue = "1") Long id, Model model) { // 假设从数据库获取用户信息,这里简化处理直接创建示例对象 User user = new User(id, "John Doe", "[email protected]", 30); // 将用户对象放入Model中,Thymeleaf模板可以从这里获取数据 model.addAttribute("user", user); return "user"; // 返回模板名称,对应templates目录下的user.html } // 简化的User类示例 public static class User { private Long id; private String name; private String email; private int age; public User(Long id, String name, String email, int age) { this.id = id; this.name = name; this.email = email; this.age = age; } // Getter and Setter methods... } }

4. 访问页面 现在,如果你启动Spring Boot应用并通过浏览器访问http://localhost:8080/user(假设应用运行在本地8080端口),你会看到根据user.html模板渲染出的用户信息页面。

四. Thymeleaf语法

Thymeleaf是一款用于Web和独立环境的现代服务器端Java模板引擎,它设计得非常贴近HTML,易于理解且功能强大。在Spring Boot项目中,Thymeleaf常用于动态生成HTML页面。下面是一些Thymeleaf核心语法的示例及其详细讲解:

1. 变量表达式 (${...}) 用于输出变量的值,等同于EL表达式。

Hello, ${user.name}!

详细讲解:user.name表示从上下文中获取user对象的name属性,并将其输出到页面上。

 

2. 文本替换 (th:text) 用于替换元素内的文本内容。

Default Greeting

详细讲解:如果greeting变量存在,那么

标签内的文本将被greeting变量的值替换。

 

3. 条件判断 (th:if, th:unless) 用于条件性地渲染元素。

Welcome Admin! Please log in. 详细讲解:th:if当条件为真时渲染元素,th:unless则当条件为假时渲染。

 

4. 循环 (th:each) 用于遍历集合或数组。

详细讲解:遍历items集合,对于每个item,生成一个元素并显示其内容。

 

5. 属性修改 (th:href, th:class, etc.) 用于动态设置HTML元素的属性。

View Profile Status 详细讲解:th:href使用链接表达式生成URL,th:class根据条件动态改变CSS类。

 

6. 消息国际化 (#{...}) 用于显示国际化消息。

Welcome Message 详细讲解:#{welcome.message}会根据用户的区域设置查找相应的消息键值。

 

7. 片段 (th:insert, th:replace, th:include) 用于复用模板代码。

Header Content 详细讲解:th:fragment定义一个可重用的片段,th:insert、th:replace或th:include用于在其他地方插入该片段。

 

8. 表达式切换 (th:switch, th:case) 用于基于不同条件渲染不同的内容。

Admin

User

Guest

详细讲解:根据user.role的值,选择性地渲染对应的

元素,th:case="*"表示默认情况。

五. 数据绑定

在Spring Boot应用中,Thymeleaf模板引擎与后端数据的绑定是通过Spring MVC的模型(Model)对象来实现的。数据绑定使得前端模板可以直接访问后端控制器(Controller)传递的数据,实现动态内容的渲染。下面通过一个示例来详细讲解数据绑定的过程。

1. 控制器中准备数据 首先,在控制器类中,你需要创建一个方法来处理请求,并将数据放入Model对象中。这个数据随后可以在Thymeleaf模板中访问。

import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class DataBindingController { @GetMapping("/example") public String examplePage(Model model) { // 准备数据 Person person = new Person("Alice", "[email protected]", 30); // 将数据放入Model model.addAttribute("person", person); // 返回视图名称,对应templates目录下的example.html return "example"; } // 示例Person类 public static class Person { private String name; private String email; private int age; public Person(String name, String email, int age) { this.name = name; this.email = email; this.age = age; } // Getter and Setter省略... } }

2. Thymeleaf模板中使用数据 接着,在Thymeleaf模板文件中,你可以使用Thymeleaf表达式来访问和显示这些数据。

Data Binding Example User Profile

Name:

Email:

Age:

 

详细讲解

模型对象(Model):在Spring MVC中,Model是一个接口,用来携带数据从控制器到视图。通过model.addAttribute()方法,我们可以将任何Java对象添加到Model中,然后在视图中通过其名称访问。Thymeleaf表达式:在模板文件中,使用th:text属性来插入动态数据。${...}是Thymeleaf的标准表达式语法,用于获取Model中的数据。例如,${person.name}获取名为person的对象的name属性值。数据绑定:数据绑定的过程是自动的,Spring MVC框架会将Model中的数据与Thymeleaf模板中的表达式匹配,从而实现数据的动态渲染。这意味着,只要在控制器中正确添加了数据,并在模板中使用正确的表达式引用,数据就能正确显示。

六. 表单处理

在Spring Boot应用中,使用Thymeleaf处理表单是构建动态Web应用的重要环节。Thymeleaf提供了丰富的特性来简化表单的创建和数据绑定。下面通过一个示例来详细讲解如何在Spring Boot应用中使用Thymeleaf处理表单。

1. 创建表单模型 首先,定义一个简单的表单模型类,用于封装表单数据。

// 表单模型类 public class UserForm { private String username; private String password; private String email; // Getter和Setter省略... }

2. 控制器处理方法 接下来,创建控制器方法来处理表单提交和显示。

import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { @GetMapping("/register") public String showRegistrationForm(UserForm userForm) { return "registration"; // 对应templates下的registration.html } @PostMapping("/register") public String processRegistration(UserForm userForm, BindingResult result, Model model) { if (result.hasErrors()) { return "registration"; // 如果有错误,重新显示表单 } // 这里可以添加保存用户逻辑 model.addAttribute("successMessage", "注册成功!"); return "result"; // 成功页面 } }

3. Thymeleaf表单模板 在src/main/resources/templates目录下创建registration.html,使用Thymeleaf语法构建表单。

User Registration User Registration Username: Password: Email: Register

详细讲解

th:object: 在表单标签中使用th:object属性绑定表单模型对象。在这个例子中,userForm对象的属性将与表单字段一一对应。th:field: 用于表单输入元素,它会自动处理输入值的绑定和回显。例如,th:field="*{username}"会绑定到UserForm类的username属性。表单提交地址: th:action="@{/user/register}"动态生成表单提交的URL,适应不同的环境配置。数据校验: 虽然本例未展示,但Spring Boot和Thymeleaf支持JSR-303 Bean Validation,可以在模型类上添加校验注解(如@NotNull, @Size等),并在控制器中通过BindingResult检查校验结果。错误处理: 如果表单提交后有错误,可以通过BindingResult获取错误信息,并在模板中显示。成功消息: 在表单处理完成后,可以通过Model向模板传递成功消息,如model.addAttribute("successMessage", "注册成功!"),并在模板中通过Thymeleaf表达式显示。

七. 国际化(I18n)

在Spring Boot应用中集成Thymeleaf模板引擎并实现国际化(I18n)功能,可以让应用支持多语言界面,提高用户体验。以下是实现这一功能的步骤和代码示例。

1. 配置国际化资源文件 在src/main/resources目录下创建国际化资源文件,通常命名为messages.properties(默认语言,如英语)、messages_zh_CN.properties(简体中文)等。 例如,messages.properties:

greeting=Hello, World!

messages_zh_CN.properties:

greeting=你好,世界!

2. 配置Spring Boot 在application.properties或application.yml中配置国际化基础设置。application.properties:

spring.messages.basename=i18n/messages

application.yml:

spring: messages: basename: i18n/messages

4. 在Thymeleaf模板中使用国际化标签 在Thymeleaf模板中,使用th:text属性和#{...}语法来显示国际化消息。

Internationalized Greeting Default Greeting

5. 设置语言切换 为了支持用户切换语言,你需要在应用中提供一种机制来改变用户的语言偏好。这通常涉及到在请求中传递一个参数(如lang)来指定语言代码,并在控制器中处理这个参数,然后设置到LocaleContextHolder。示例控制器方法:

import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.LocaleResolver; @Controller public class LanguageController { @RequestMapping(value = "/switchLanguage", method = RequestMethod.GET) public String switchLanguage(@CookieValue(value = "locale", required = false) String locale, LocaleResolver localeResolver) { if (locale != null) { localeResolver.setLocale(LocaleContextHolder.getRequestAttributes(), new Locale(locale)); } return "redirect:/"; // 重定向到主页或其他页面 } }

6. 用户界面语言切换 在前端,提供链接让用户选择语言,并在点击时发送请求更新语言设置。这通常通过JavaScript或直接在链接中携带参数实现。

English 简体中文 八. 编译器和方言配置

在Spring Boot中集成Thymeleaf时,可以通过配置调整Thymeleaf的编译器行为和方言,以优化性能或满足特定需求。下面是关于编译器和方言配置的详细讲解及代码示例。

1. Thymeleaf编译器配置 Thymeleaf提供了对模板的预编译选项,可以提升应用启动时的性能。在Spring Boot应用中,可以通过配置文件来调整编译器设置。application.properties示例:

# 开启模板缓存,默认为true,生产环境推荐开启 spring.thymeleaf.cache=true # 设置模板模式,默认为HTML5 spring.thymeleaf.mode=HTML5 # 模板编码,确保与你的文件编码一致 spring.thymeleaf.encoding=UTF-8 # 视图前缀,Thymeleaf会自动在该前缀后拼接模板文件名 spring.thymeleaf.prefix=classpath:/templates/ # 视图后缀,Thymeleaf会寻找以此为后缀的文件 spring.thymeleaf.suffix=.html

2. 高级编译器配置 对于更高级的编译器配置,可以通过创建一个Thymeleaf配置类来定制。例如,调整模板解析器的设置:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring5.view.ThymeleafViewResolver; @Configuration public class ThymeleafConfig { @Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setPrefix("classpath:/templates/"); resolver.setSuffix(".html"); resolver.setCacheable(true); // 是否开启缓存 resolver.setTemplateMode("HTML5"); // 设置模板模式 return resolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver()); return engine; } @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); resolver.setCharacterEncoding("UTF-8"); return resolver; } }

3. Thymeleaf方言配置 Thymeleaf支持方言(Dialects)来扩展其标准表达式语言和标签。虽然大多数情况下使用默认方言就足够,但你可以添加自定义方言或第三方方言来增强功能。 假设你要添加一个自定义方言,可以通过配置Thymeleaf引擎来实现:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.dialect.AbstractProcessorDialect; import org.thymeleaf.processor.IProcessor; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class ThymeleafCustomDialectConfig { @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new MyCustomDialect()); // 注册自定义方言 return engine; } // 自定义方言示例 public static class MyCustomDialect extends AbstractProcessorDialect { public MyCustomDialect() { super("My Custom Dialect", "custom", 1000); } @Override public Set getProcessors(String dialectPrefix) { // 实现处理器逻辑 return Collections.emptySet(); // 示例中返回空集,实际应添加处理器 } } } 九. 静态资源处理

在Spring Boot应用中,静态资源(如CSS、JavaScript、图片等)的处理是自动配置的,但有时可能需要进行一些自定义配置。以下是如何管理和配置静态资源的详细说明和示例。

默认配置 Spring Boot默认配置如下:

静态资源默认存放于src/main/resources/static(或public)目录下。静态资源URL映射默认为/**,意味着所有未被其他路由处理的请求都会被当作静态资源请求处理。Thymeleaf模板默认查找src/main/resources/templates目录下的模板文件。

自定义配置 如果你需要自定义静态资源的位置或URL映射,可以通过配置文件来实现。application.properties示例

# 自定义静态资源位置 spring.resources.static-locations=classpath:/custom-static/,classpath:/public/ # 自定义静态资源URL前缀 spring.mvc.static-path-pattern=/assets/** # 禁用默认的静态资源处理(如果需要完全自定义) spring.resources.add-mappings=false

Thymeleaf与静态资源 在Thymeleaf模板中引用静态资源时,应确保路径正确无误。由于Spring Boot默认配置,静态资源路径通常是相对于应用根路径的,因此引用样式或脚本时不需要包含/static或自定义的前缀。

@{...}是Thymeleaf的URL语法,它会自动处理资源路径,确保它们是上下文相关的。

 

注意事项

当使用Thymeleaf时,确保在HTML头部正确设置了xmlns:th命名空间。如果遇到静态资源404错误,检查资源路径是否正确,以及是否正确配置了静态资源的处理路径。如果静态资源位于jar包内,确保Spring Boot能够访问jar内部的资源。 十. 测试

在Spring Boot应用中,集成Thymeleaf模板后,进行单元测试和集成测试是非常重要的,以确保模板正确渲染以及与后端逻辑的交互无误。这里将分别介绍使用JUnit和MockMvc进行单元测试的方法。

1. 单元测试 - 测试Thymeleaf模板渲染 对于Thymeleaf模板的直接渲染测试,可以使用Thymeleaf的测试工具,但更常见的是通过集成测试来间接验证模板输出,因为模板通常与后端逻辑紧密相关。

 

2. 集成测试 - 使用MockMvc测试 集成测试通过模拟HTTP请求来验证整个请求-响应周期,包括模板渲染。Spring Boot提供了MockMvc来方便地进行这类测试。

准备工作 确保你的项目中已经添加了Spring Boot Test依赖,通常在pom.xml或build.gradle中已经默认包含。pom.xml:

org.springframework.boot spring-boot-starter-test test

测试示例 假设你有一个简单的控制器,渲染一个包含欢迎信息的页面。

// 控制器示例 @GetMapping("/") public String index(Model model) { model.addAttribute("message", "Welcome to our application!"); return "index"; }

对应的Thymeleaf模板src/main/resources/templates/index.html:

Welcome Default Message

编写测试 使用MockMvc进行集成测试,验证index页面的渲染。

import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(controllers = YourController.class) // 替换YourController为实际的控制器类名 class YourControllerTest { @Autowired private MockMvc mockMvc; @Test void shouldReturnWelcomeMessage() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(content().string(containsString("Welcome to our application!"))); } }

详细讲解

@WebMvcTest: 这个注解告诉Spring Boot只加载Web相关的组件,包括控制器、配置、转换器、过滤器等,非常适合进行Web层的单元测试。MockMvc: 是Spring提供的一个模拟的MVC测试框架,允许你在没有真实服务器的情况下发起HTTP请求,并验证响应。mockMvc.perform(): 发起一个HTTP请求。在这个例子中,我们发起一个GET请求到根路径/。andExpect(): 用于断言响应的状态或内容。status().isOk()检查HTTP状态码是否为200,content().string(...)则检查响应内容是否包含预期的字符串。


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有