使用模板引擎的原因
- JSP 是通过 Java 代码 + 数据 + HTML 的方式最终生产出HTML内容响应,同时JSP会生成 class 文件,与 Java 语言和 servlet 有绑定关系
- Thymeleaf 和 freemaker 等引擎模板技术则是通过 数据 + 模板文件 的方式最终生产出 HTML 内容响应,并不会生成 class 文件,也不依赖于 servlet 规范。
- 模板引擎优于 JSP 的技术原因
- 松耦合
- 前后端分离更加彻底
- 性能优化
- 灵活度高
整合Thymeleaf
引入Thymeleaf依赖
- spring boot 官方提供 Thymeleaf 的场景启动器 spring-boot-starter-thymeleaf,在 pom.xml 文件中添加即可,添加部分对照如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf 模板引擎依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
创建模板文件
模板默认后缀名为html,在 resource/templates 目录新建模板文件 thymeleaf.html,新增文件后,首先在模板文件的标签中导入 Thymeleaf 的名称空间
引入该命名空间的目的是为了获得在开发过程中的代码提示提高编写效率
<html lang="en" xmlns:th="http://www.thymeleaf.org">
加入简单的显示内容
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf demo</title>
</head>
<body>
<p>description字段值为:</p>
<p th:text="${description}">这里显示的是 description 字段内容</p>
</body>
</html>
编辑Controller代码
在 controller 包下新增 ThymeleafController.java 文件,将模板文件所需的 description 字段赋值并转发至模板文件,编码如下
package ltd.newbee.mall.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String hello(HttpServletRequest request, @RequestParam(value = "description", required = false, defaultValue = "springboot-thymeleaf") String description) {
request.setAttribute("description", description);
return "thymeleaf";
}
}
实时调试
让Thymeleaf页面能够实时的刷新而不需要重启服务器。
-
打开IDEA->Setting,将下面的选项【Build project automatically】给勾选上:
-
然后按下快捷键【Ctrl + Alt + Shift + /】,召唤出【Maintenance】菜单,进入【Registry】:
-
把【compiler.automake.allow.when.app.running】这个选项的 √ 给打上:
-
然后再把【application.properties】弄成这个样子:
#thymeleaf 配置 spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html #缓存设置为false, 这样修改之后马上生效,便于调试 spring.thymeleaf.cache=false
-
然后重启项目