Thymeleaf是一种现代的基于服务器端的Java 模板引擎技术,也是一个优秀的面向Java的XML、XHTML、HTML5页面模板,它具有丰富的标签语言、函数和表达式,在使用Spring Boot框架进行页面设计时,一般会选择Thymeleaf模板
在HTML页面上使用Thymleaf标签,Thymleaf标签能够动态地替换掉静态内容,使页面动态展示。
为了大家更直观的认识Thymeleaf,下面展示了一个在HTML文件中嵌入Thymeleaft的页面文件,示例代码如下:
DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="../../css/xx.css" th:href="@{/css/xx.css}"/>
<title>Titletitle>
head>
<body>
<p th:text="${hello}">欢迎学习Thymleafp>
body>
html>
上述代码中,“xmlns:th=“http://www.thymeleaf.org””用于引入Thymeleaf模板引擎标签,使用关键字”th“标注标签是Thymeleaf模板提供的标签,其中,”th:href“用于引入外部样式文件,”th:text“用于动态显示标签文本内容。
除此之外,Thymeleaf模板提供了很多标签,接下来,通过一张表格展示Thymeleaf常用标签
| th:标签 | 说明 |
|---|---|
| th:insert | 布局标签,替换内容到引入的文件 |
| th:replace | 布局标签,替换整个标签到引入的文件 |
| th:each | 元素遍历(类似JSP中的c:forEach标签) |
| th:if | 条件判断,如果为真 |
| th:unless | 条件判断,如果为假 |
| th:switch | 条件判断,进行选择性匹配 th:case |
| th:case | 条件判断,进行选择性匹配 th:switch |
| th:value | 属性值修改,指定标签属性值 |
| th:href | 用于设定链接地址 |
| th:src | 用于设定链接地址 |
| th:text | 用于指定标签显示的文本内容 |
Thymeleaf模板引擎提供了多种标准表达式语法,接下来,通过一张表格展示其主要语法及说明
| 说明 | 表达式语法 |
|---|---|
| 变量表达式 | ${…} |
| 选择变量表达式 | *{…} |
| 消息表达式 | #{…} |
| 链接URL表达式 | @{…} |
| 片段表达式 | ~{…} |
变量表达式${…}主要用于获取上下文中的变量值,示例代码如下:
<p th:text=${title}>这是一个标题p>
示例中使用了Thymeleaf模板的变量表达式${…}用来动态获取P标签中的内容,如果当前程序没有启动或者当前上下文中不存在title变量,该片段会显示标签默认值”这是一个标题“;如果当前上下文中存在title变量并且程序已经启动,当前P标签中的默认文本内容将会被title变量的值所替换,从而达到模板引擎页面数据动态替换的效果。
通过Thymeleaf为变量所在域提供了一些内置对象,具体如下所示
#ctx:上下文对象
#vars:上下文变量
#local:上下文区域设置
#request:【仅限Web Context】HttpServletRequest对象
#response:【仅限Web Context】HttpServletResponse对象
#session:【仅限Web Context】HttpSession对象
#servletContext:【仅限Web Context】HttpServletContext对象
结合上述内置对象的说明,假设要在Thymeleaf模板引擎页面中动态获取当前国家信息,可以使用#locale内置对象,示例代码如下
The locale country is <span th:text="${#locale.country}">USspan>
上述代码中,使用th:text="${#locale.country}"动态获取当前用户所在的国家信息,其中span标签内默认内容为US,程序启动后通过浏览器查看当前页面时,Thymleaf会通过浏览器语言设置来识别当前用户所在国家信息,从而实现动态替换。
选择变量表达式和变量表达式用法类似,一般用于从被选定对象而不是上下文中获取属性值,如果没有选定对象,则和变量表达式一样,示例代码如下
<div th:object="${book}">
<p>title: <span th:text="*{title}">标题span>p>
div>
*{title}选择变量表达式获取当前指定对象book的title属性值。
消息表达式#{…}主要用于Thymeleaf模板页面国际化内容的动态替换和展示,使用消息表达式#{…}进行国际化设置时,还需要提供一些国家化配置文件,关于消息表达式的使用,我们在4 国际化中做详细说明
链接表达式@{…}一般用于页面跳转或者资源的引入,在Web开发中占据着非常重要的地位,并且使用也非常频繁,示例代码如下:
<a th:href="@{http://localhost:8443/order/details{orderId=${o.id}}}">viewa>
<a th:href="@{/order/details{orderId=${o.id}}}">viewa>
上述代码中,链接表达式@{…}分别编写了绝对链接地址和相对链接地址。在有参表达式中,需要按照@{路劲{参数名=参数值,参数名=参数值…}}的形式编写,同时改参数的值可以使用变量表达式来传递动态参数值。
片段表达式 ~{…}用来标记一个片段模板,并根据需要移动或传递给其他模板。其中,最常见的用法是使用th:insert或th:replace属性插入片段,示例代码如下:
<div th:insert="~{thymeleafDemo::title}">div>
上述代码中,使用th:insert属性将title片段模板引用到该div标签中。thymeleafDemo为模板名称,Thymeleaf会自动查找”/resources/templates/“目录下的thymeleafDemo模板,title为片段名称
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
其次,在全局配置文件中配置Thymeleaf模板的一些参数。一般Web项目都会使用下列配置,示例代码如下
spring:
thymeleaf:
cache: true # 启用模板缓存
encoding: UTF-8 # 模板编码
mode: HTML5 # 应用于模板的模板模式
prefix: classpath:/templates/ # 指定模板页面存放路径
suffix: .html # 指定模板页面名称的后缀
上述配置中,cache表示是否开启Thymeleaf模板缓存,默认为true,在开发过程中通常会关闭缓存,保证项目调试过程中数据能够及时响应;prefix指定了Thymeleaf模板页面的存放路径,默认为classpath:/templates/;suffix指定了Thymeleaf模板页面的名称后缀,默认为.html
spring:
thymeleaf:
cache: false # thymeleaf页面缓存设置(默认为true),开发中方便调试代码设置为false。
@Controller
public class LoginController{
/**
* 获取当前时间并跳转到登录页面
*/
@RequestMapping("/loginPage")
public String loginPage(Model model){
model.addAttribute("currentTime",LocalDateTime.now());
return "login";
}
}
loginPage()方法用于向登录页面login.html跳转,同时携带了当前时间currentTime。
DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>用户登录页面title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/login/css/signin.css}" rel="stylesheet">
head>
<body>
<form>
<h1>请登录h1>
<input type="text" th:placeholder="用户名" required="" autofocus=""/>
<input type="password" th:placeholder="密码" required=""/>
<button type="submit">登录button>
<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
form>
body>
html>
通过“xmlns:th=“http://www.thymeleaf.org””引入了Thymeleaf模板标签
使用“th:href”引入了两个外联样式文件
使用“th:text”引入了后台动态传递过来的当前时间currentTime

在项目的类路径resources下创建名称为i18n的文件夹,并在该文件夹中根据需要编写对应的多语言国际化文件login.properties、login_zh_CN.properties和login_en_US.properties文件
login.properties
login.tip=请登录
login.username=用户名
login.password=密码
login.buttom=登录
login_zh_CN.properties
login.tip=请登录
login.username=用户名
login.password=密码
login.buttom=登录
login_en_US.properties
login.tip=Please sign in
login.username=Username
login.password=Password
login.buttom=Login
login.properties为自定义默认语言配置文件,login_zh_CN.properties为自定义中文国际化文件,login_en_US.properties为自定义英文国际化文件
需要说明的是,Spring Boot默认识别的语言配置文件为类路径resources下的message.properties;其他语言国际化文件的名称必须严格按照“文件前缀名_语言代码_国家代码.properties”的形式命名
本示例中,在项目类路径resources下自定义了一个i18n包用于统一配置管理多语言配置文件,并将项目默认语言配置文件名自定义为login.properties,因此,后续还必须在项目全局配置中进行国际化文件基础名配置,才能引用自定义国际化文件
在application.yml全局配置文件中,添加国际化文件基础名设置。
spring:
thymeleaf:
cache: false # thymeleaf页面缓存设置(默认为true),开发中方便调试代码设置为false。
messages:
basename: i18n.login # 配置国际化文件基础名
“spring.messages.basename=i18n.login”设置了自定义国际化文件的基础名。其中,i18n表示国际化文件相对项目类路径resources的位置,login表示多语言文件的前缀名。如果开发者完全按照Spring Boot默认识别机制,在项目类路径resources下编写messages.properties等国际化文件,可以省略国际化文件基础名的配置
DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>用户登录页面title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/login/css/signin.css}" rel="stylesheet">
head>
<body>
<form>
<h1 th:text="#{login.tip}">请登录h1>
<input type="text" th:placeholder="#{login.username}" required="" autofocus=""/>
<input type="password" th:placeholder="#{login.password}" required=""/>
<button type="submit" th:text="#{login.buttom}">登录button>
<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
form>
body>
html>
在完成上一步中多语言国际化文件的编写和配置后,就可以正式在前端页面中结合Thymeleaf模板相关属性进行国际化语言设置和展示,不过这种实现方式默认是使用请求头中的语言信息(浏览器语言信息)自动进行语言切换的,有些项目还会提供手动语言切换的功能,这就需要定制区域解析器了
在项目中创建名为com.lxsh.config的包,并在该包下创建一个用于定制国家化功能区域信息解析器的自定义配置类MyLocaleResolver
@Configuration
public class MyLocaleResolver implements LocaleResolver {
//自定义区域解析器
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest){
//获取页面手动切换传递的语言参数
String language = httpServletRequest.getParameter("language");
//获取请求头自动传递的语言参数 Accept-Language
String header = httpServletRequest.getHeader("Accept-Language");
Locale locale = null;
//如果手动切换参数不为空,就根据手动参数进行语言切换,否则默认根据请求头信息切换
if(StringUtils.isNotEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0],split[1]);
} else {
String[] headers= header.split(",");
String[] split = headers.split("-");
locale = new Locale(split[0],split[1]);
}
return locale;
}
//将自定义的MyLocaleResolver重新注册成一个类型为LocaleResolver的Bean组件
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
页面添加中英文切换功能
DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>用户登录页面title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/login/css/signin.css}" rel="stylesheet">
head>
<body>
<form>
<h1 th:text="#{login.tip}">请登录h1>
<input type="text" th:placeholder="#{login.username}" required="" autofocus=""/>
<input type="password" th:placeholder="#{login.password}" required=""/>
<button type="submit" th:text="#{login.buttom}">登录button>
<p>当前时间:<span th:text="${currentTime}">2022-02-30 10:30:00span>p>
form>
<a th:href="@{/loginPage(language='zh_CN')}">中文a>
<a th:href="@{/loginPage(language='en_US')}">Englisha>
body>
html>