Thymeleaf
Thymeleaf是当今比较流行的模板框架,并且是Spring Boot官方推荐使用的模板框架。本小节介绍Spring Boot框架如何使用Thymeleaf,并且会对Thymeleaf框架的使用方法进行介绍。
首先创建项目,在项目中加入spring-boot-starter-thymeleaf依赖。这里需要提醒的是,由于Thymeleaf对HTML的校验特别严格,比如标签没有结束等可能会对不熟悉者造成未知的困惑,因此我们还需要加入nekohtml的依赖来避免这个“坑”。Thymeleaf依赖如代码
<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>
<!-- 取出html严格校验-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
完成依赖的配置之后,我们需要在配置文件中对Thymeleaf进行配置,比如编码格式、缓存设置、文件前后缀等。配置文件内容如代码
server.port=8089
#缓存是否开启,开发时建议关闭
spring.thymeleaf.cache=false
#编码格式
spring.thymeleaf.encoding=UTF-8
#thymeleaf对html的校验很严格,用这个去除严格校验
spring.thymeleaf.mode=LEGACYHTML5
#模板文件前缀
spring.thymeleaf.prefix=classpath:/templates/
#模板文件后缀
spring.thymeleaf.suffix=.html
到这里,准备工作已经完成。需要做的是创建一个Controller和HTML进行测试。新建一个IndexController,我们先写一个简单的路由跳转方法并且传一个字符串值进行测试。IndexController内容如代码
package com.shrimpking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/12/21 10:18
*/
@Controller
public class IndexController
{
@GetMapping("/")
public String index(ModelMap modelMap){
modelMap.addAttribute("msg","hello, thymeleaf");
return "index";
}
}
然后,在src/mian/resources/templates下新建一个index.html(需要结合配置文件中spring.thymeleaf.prefix的配置信息存放HTML),使用th:text="${msg}"来接收后台传来的数据。index.html内容如代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
启动项目,在浏览器上访问http://localhost:8089,可以看到有如下显示:
其实到这里Spring Boot整合Thymeleaf已经完成,但是为了方便后面章节的使用,笔者在这里再介绍一下Thymeleaf模板的常用语法。
th:text 设置当前元素的文本内容。
• th:value 设置当前元素的值。
• th:each 循环遍历元素,一般配合上面两者使用。
• th:attr 设置当前元素的属性。
• th:if th:switch th:case th:unless 用作条件判断。
• th:insert th:replace th:incloud 代码块引入,一般用作提取公共文件,或者引用公共静态文件等。
当然,Thymeleaf也提供了一些内置方法供我们使用,比如:
• #numbers 数字方法。
• #dates 日期方法。
• #calendars 日历方法。
• #strings 字符串方法。
• #lists 集合方法。
• #maps 对象方法。
关于Thymeleaf先了解到这里,后面的章节会对它有具体的实战使用,这里就不再赘述了。