6.1.1 模板引擎
在现代Web开发中,模板引擎是不可或缺的一部分。它们帮助我们分离业务逻辑与前端展示,使前端开发更加高效、灵活。在众多模板引擎中,Thymeleaf以其简洁的语法、非侵入式的设计以及与Spring框架的无缝集成,逐渐成为许多开发者的首选。
本文将详细探讨Thymeleaf模板引擎的特点、使用场景、基本语法及其与Spring Boot的整合方式。
Thymeleaf的特点
1. 非侵入式模板设计
Thymeleaf的设计遵循了非侵入式的原则,这意味着开发者可以直接使用HTML作为模板语言,只需在需要的地方添加Thymeleaf特定的属性前缀(默认为th:
)。这种设计方式不仅使得前端设计师可以更加专注于页面设计,无需担心模板引擎的特定语法,还降低了后端开发人员的学习成本。
2. 支持HTML5标准
Thymeleaf完全支持HTML5标准,提供了丰富的标签库来处理条件语句、循环、国际化、URL处理等常见Web开发任务。这些标签的语法设计得非常直观,使得模板易于理解和维护。
3. 高性能
尽管Thymeleaf的语法简洁且功能强大,但它并未牺牲性能。在服务器端执行时,Thymeleaf会首先将模板转换为一种优化的执行结构,这种结构使得模板的渲染过程非常高效。
4. 与Spring框架无缝集成
Thymeleaf与Spring Framework无缝集成,为基于Spring的应用提供了强大的模板解决方案。特别是Spring Boot,更是将Thymeleaf作为默认的模板引擎之一,进一步简化了配置和使用过程。
5. 开箱即用
Thymeleaf提供了Spring标准方言以及一个与Spring MVC完美集成的可选模块,可以快速地实现表单绑定、属性编辑器、国际化等功能。这些功能极大地提高了开发效率,降低了开发成本。
6.2 快速上手
1.构建项目:
之前已经教过怎么建项目了自己去翻一下
2.添加依赖
不管采用那种构建项目方式,项目准备好后,需要配置pom.xml文件,添加相应的依赖(启动器),pom.xml文件中添加的依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
3.application.properties添加配置
spring.thymeleaf.cache=false
4.Model 准备
在之前的学习中,entity、Repository已经开发完成(其实几乎不用写什么代码),此处只需要编写好Service即可,提供基本的CRUD功能
public interface UserService {
User login(String usrName, String usrPassword);
int addUser(User user);
int deleteUser(Long usrId);
int updateUser(User user);
User getUser(Long usrId);
List<User> findAllUsers();
}
5.控制器开发
在com.bdqn.crm.web.controller包下创建 ExampleController,用于演示:
@Controller
public class ExampleController {
@Resource
private UserService userService;
@GetMapping(value = "hello/{id}")
public String getUser(@PathVariable("id") Long usrId, Model model){
User user = userService.getUser(usrId);
model.addAttribute("user",user);
return "demo/hello";
}
6.开发页面
在resource/templates/demo 目录下新建hello.html,Kind(种类)选择 HTML5 file
<!DOCTYPE html>
<!--加入对Thymeleaf模板引擎支持-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="stylesheet" th:href="@{/css/index.css}" />
</head>
<body>
欢迎您,<span th:text="${user.usrName}">张三</span>!
</body>
</html>