thymeleaf是springboot官方推荐使用的java模板引擎,在springboot的参考指南里的第28.1.10 Template Engines中介绍并推荐使用thymeleaf,建议我们应该避免使用jsp,jsp的本质是一个java的servlet类,jsp引擎将jsp的内容编译成.class,"out.write"输出到response再响应到浏览器,虽然java是一次编译,到处运行,但也大大增加了服务器压力,而且jsp将后台java语言嵌入页面,还要放入服务容器才能打开,前后端不分离,严重增加了前端工程师的开发工作、效率。
thymeleaf官网对thymeleaf的介绍:
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.
thymeleaf使用教程,骚操作:鼠标右键,翻译成简体中文再看。
thymeleaf使用th属性赋予每个标签与后台交互的能力,当html文件在本地直接用浏览器打开,浏览器引擎会忽略掉th属性,并正常渲染页面,当把html文件放到服务容器访问,th属性与后台交互,获取数据替换原先的内容,这样前端工程师在编写html页面时,在本地开发,正常实现页面逻辑效果即可,数据先写死,当放到服务容器时数据从后台获取。
spring对thymeleaf的配置,来自springboot参考手册,Common application properties:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-properties
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names=# Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response.
spring.thymeleaf.reactive.media-types=# Media types supported by the view technology.
spring.thymeleaf.render-hidden-markers-before-checkboxes=false # Whether hidden form inputs acting as markers for checkboxes should be rendered before the checkbox element itself.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.servlet.produce-partial-output-while-processing=true # Whether Thymeleaf should start writing partial output as soon as possible or buffer until template processing is finished.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order=# Order of the template resolver in the chain.
spring.thymeleaf.view-names=# Comma-separated list of view names (patterns allowed) that can be resolved.
maven引入依赖
<!--Thymeleaf模板依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
项目结构
thymeleaf默认,页面跳转默认路径:src/main/resources/templates,静态资源默认路径:src/main/resources/static;
yml配置文件
我们也可以在配置文件中修改它:classpath:/view/
controller页面跳转
使用ModelAndView进行跳转,将数据add进去
@RequestMapping("/login.do")
public ModelAndView login(User user){
Result result=userService.login(user);
ModelAndView mv=new ModelAndView();
mv.addObject("newText","你好,Thymeleaf!");
mv.addObject("gender","1");
mv.addObject("userList",result.getData());
if(result.getData()!=null) {
mv.addObject("loginUser",result.getData());
}
mv.setViewName("index.html");
return mv;
}
html页面取值
引入命名空间,避免校验错误<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<!--解决idea thymeleaf 表达式模板报红波浪线-->
<!--suppress ALL -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>srpingboot</title>
</head>
<body>
<!-- 属性替换,其他属性同理 -->
<h1 th:text="${newText}">Hello World</h1>
<!--
设置多个attr
th:attr="id=${user.id},data-xxx=${user.xxx},data-yyy=${user.yyy}"
片段的使用、传值和调用
<div th:fragment="common(text1,text2)">
...
</div>
th:insert 是最简单的:它只是插入指定的片段作为其主机标签的主体。
<div th:insert="base ::common(${text1},${text2})"></div>
th:replace实际上用指定的片段替换它的主机标签。
<div th:replace="base ::common(${text1},${text2})"></div>
三目表达式:
<h3 th:text="${loginUser !=null} ? ${loginUser.username} : '请登录'"></h3>
-->
<!-- if-else -->
<h3 th:if="${loginUser} ne null" th:text="${loginUser.username}"></h3>
<h3 th:unless="${loginUser} ne null">请登录</h3>
<!-- switch -->
<div th:switch="${gender}">
<p th:case="'1'">男</p>
<p th:case="'0'">女</p>
<!-- th:case="*" 类似switch中的default -->
<p th:case="*">其他</p>
</div>
<!--
each
其中,iterStat参数为状态变量,常用的属性有
index 迭代下标,从0开始
count 迭代下标,从1开始
size 迭代元素的总量
current 当前元素
-->
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>created</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr th:each="user,iterStat : ${userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td th:text="${user.created}"></td>
<td th:text="${user.description}"></td>
</tr>
</tbody>
</table>
</body>
<!-- 引入静态资源 -->
<script th:src="@{/js/jquery-1.9.1.min.js}" type="application/javascript"></script>
</html>
本地打开
服务容器打开,登录失败页面效果
服务容器打开,登录成功页面效果
简单表达
变量表达式: ${...}
选择变量表达式: *{...}
消息表达式: #{...}
链接网址表达式: @{...}
片段表达式: ~{...}
字面
文本文字:'one text','Another one!',...
号码文字:0,34,3.0,12.3,...
布尔文字:true,false
空字面: null
文字标记:one,sometext,main,...
文字操作:
字符串连接: +
文字替换: |The name is ${name}|
算术运算
二元运算符:+,-,*,/,%
减号(一元运算符): -
布尔运算
二元运算符:and,or
布尔否定(一元运算符): !,not
比较和平等
比较:>,<,>=,<=(gt,lt,ge,le)
等值运算符:==,!=(eq,ne)
条件运算符
if-then: (if) ? (then)
if-then-else: (if) ? (then) : (else)
default: (value) ?: (defaultvalue)
特殊特征符
无操作: _
所有这些功能都可以组合和嵌套,例:
'User is of type ' + (user.isAdmin()?′Administrator′:(user.isAdmin()?′Administrator′:({user.type} ?: 'Unknown'))
官网表达式介绍:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
springboot+thymeleaf,前后端分离已经成为了趋势,这里进行学习记录整理,以免以后又要到处查资料。
2019-07-24补充:除此之外,thymeleaf还内置了很多对象,可以从上下文获取数据,还有好多对象的操作方法,具体请看:
附录A:表达式基本对象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects
附录B:表达式实用程序对象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects
比如:
在页面获取项目路径
//项目路径
var ctx=[[${#request.getContextPath()}]];
判断集合长度
<p th:if="${#lists.size(list)} < 25">
<p>list集合长度小于25!</p>
</p>
字符串全大写、小写
<p th:text="${#strings.toUpperCase(name)}"></p>
<p th:text="${#strings.toLowerCase(name)}"></p>
有一点要注意,使用这些内置对象,方法传参里面不需要再用${}来取值了,例如,后台传过来的名称叫name
错误使用:
<p th:text="${#strings.toUpperCase($(name))}"></p>
正确使用:
<p th:text="${#strings.toUpperCase(name)}"></p>
更多内置对象方法请看官网!
补充:本地环境不报错,Linux环境下报错,模板不存在:Error resolving template [/bam/login], template might not exist or might not be accessible by any of the configured Template Resolvers
解决:
把/去掉就可以了
代码已经开源、托管到我的GitHub、码云:
GitHub:https://github.com/huanzi-qch/springBoot
码云:https://gitee.com/huanzi-qch/springBoot
作者:huanzi-qch
出处:https://www.cnblogs.com/huanzi-qch
若标题中有“转载”字样,则本文版权归原作者所有。若无转载字样,本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.
文:https://www.xncoding.com/2017/07/01/spring/sb-thymeleaf.html
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:
目前最新版本是Thymeleaf 3,官网地址:http://www.thymeleaf.org
本篇将介绍如何在SpringBoot中集成Thymeleaf构建Web应用。
maven依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
资源目录
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件pic.jpg。 启动程序后,尝试访问http://localhost:8080/pic.jpg。如能显示图片,配置成功。
SpringBoot的默认模板路径为:src/main/resources/templates
添加页面
这里我在src/main/resources/templates下面添加一个index.html首页,同时引用到一些css、js文件,看看Thymeleaf 3的语法:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="renderer" content="webkit">
<title>首页</title>
<link rel="shortcut icon" th:href="@{/favicon.ico}"/>
<link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:href="@{/static/css/font-awesome.min.css}" rel="stylesheet"/>
</head>
<body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">
<div id="wrapper">
<h1 th:text="${msg}"></h1>
</div>
<script th:src="@{/static/js/jquery.min.js}"></script>
<script th:src="@{/static/js/bootstrap.min.js}"></script>
</body>
</html>
页面中几个地方说明一下:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
加上这个命名空间后就能在页面中使用Thymeleaf自己的标签了,以th:开头。
连接语法 th:href="@{/static/css/bootstrap.min.css}"
访问Model中的数据语法 th:text="${msg}"
这里我在页面里显示的是一个键为msg的消息,需要后台传递过来。
Thymeleaf 3的详细语法规则请参考 官网教程
编写Controller
接下来编写控制器类,将URL / 和 /index 都返回index.html页面:
@Controller
public class IndexController {
private static final Logger _logger=LoggerFactory.getLogger(IndexController.class);
/**
* 主页
*
* @param model
* @return
*/
@RequestMapping({"/", "/index"})
public String index(Model model) {
model.addAttribute("msg", "welcome you!");
return "index";
}
}
这里,我再model里面添加了一个属性,key=msg,值为welcome you!。
接下来启动应用后,打开首页看看效果如何。消息正确显示,成功!。
Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。
html<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于在展示文本-->
<h1 th:text="欢迎您来到Thymeleaf">欢迎您访问静态页面 HTML</h1>
</body>
</html>
当直接使用浏览器打开时,浏览器展示结果如下。
欢迎您访问静态页面HTML
当通过 Web 应用程序访问时,浏览器展示结果如下。
欢迎您来到Thymeleaf
Thymeleaf 的特点:
在使用 Thymeleaf 之前,首先要在页面的 html 标签中声明名称空间,示例代码如下。
htmlxmlns:th="http://www.thymeleaf.org"
在 html 标签中声明此名称空间,可避免编辑器出现 html 验证错误,但这一步并非必须进行的,即使我们不声明该命名空间,也不影响 Thymeleaf 的使用。
使用${}包裹的表达式被称为变量表达式,该表达式具有以下功能:
选择变量表达式与变量表达式功能基本一致,只是在变量表达式的基础上增加了与 th:object 的配合使用。当使用 th:object 存储一个对象后,我们可以在其后代中使用选择变量表达式(*{...})获取该对象中的属性,其中,“*”即代表该对象。
html<div th:object="${session.user}" >
<p th:text="*{fisrtName}">firstname</p>
</div>
th:object 用于存储一个临时变量,该变量只在该标签及其后代中有效,在后面的内容“th 属性”中我详细介绍。
不管是静态资源的引用,还是 form 表单的请求,凡是链接都可以用链接表达式 (@{...})。
链接表达式的形式结构如下:
例如使用链接表达式引入 css 样式表,代码如下。
html<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
消息表达式一般用于国际化的场景。结构如下。
htmlth:text="#{msg}"
注意:此处了解即可,我们会在后面的章节中详细介绍。
片段引用表达式用于在模板页面中引用其他的模板片段,该表达式支持以下 2 中语法结构:
以上语法结构说明如下:
Thymeleaf 还提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用,其中常用 th 属性及其示例如下表。
属性 | 描述 | 示例 |
th:id | 替换 HTML 的 id 属性 | <input id="html-id" th:id="thymeleaf-id" /> |
th:text | 文本替换,转义特殊字符 | <h1 th:text="hello,bianchengbang" >hello</h1> |
th:untext | 文本替换,文本替换,不转义特殊字符 | <div th:utext="'<h1>欢迎来到编程帮!</h1>'" >欢迎你</div> |
th:object | 在父标签选择对象,子标签使用 *{…} 选择表达式选取值。没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。同时即使选择了对象,子标签仍然可以使用变量表达式。 | <div th:object="${session.user}" > <p th:text="*{fisrtName}">firstname</p> </div> |
th:value | 替换 value 属性 | <input th:value="${user.name}" /> |
th:with | 局部变量赋值运算 | <div th:with="isEvens=${prodStat.count}%2==0" th:text="${isEvens}"></div> |
th:style | 设置样式 | <div th:style="'color:#F00; font-weight:bold'">编程帮 www.biancheng.net</div> |
th:onclick | 点击事件 | <td th:onclick="'getInfo()'"></td> |
th:each | 遍历,支持 Iterable、Map、数组等。 | <table> <tr th:each="m:${session.map}"> <td th:text="${m.getKey()}"></td> <td th:text="${m.getValue()}"></td> </tr></table> |
th:if | 根据条件判断是否需要展示此标签 | <a th:if="${userId==collect.userId}"> |
th:unless | 和 th:if 判断相反,满足条件时不显示 | <div th:unless="${m.getKey()=='name'}" ></div> |
th:switch | 与 Java 的 switch case语句类似通常与 th:case 配合使用,根据不同的条件展示不同的内容 | <div th:switch="${name}"> <span th:case="a">编程帮</span> <span th:case="b">www.biancheng.net</span></div> |
th:fragment | 模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段 | <footer th:fragment="footer">插入的内容</footer> |
th:insert | 布局标签;将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中 | <div th:insert="commons/bar::footer"></div> |
th:replace | 布局标签;使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签 | <div th:replace="commons/bar::footer"></div> |
th:selected | select 选择框选中 | <select> <option>---</option> <option th:selected="${name=='a'}"> 编程帮 </option> <option th:selected="${name=='b'}"> www.biancheng.net </option></select> |
th:src | 替换 HTML 中的 src 属性 | <img th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" /> |
th:inline | 内联属性;该属性有 text、none、javascript 三种取值,在 <script> 标签中使用时,js 代码中可以获取到后台传递页面的对象。 | <script type="text/javascript" th:inline="javascript"> var name=/*[[${name}]]*/ ianchengbang'; alert(name)</script> |
th:action | 替换表单提交地址 | <form th:action="@{/user/login}" th:method="post"></form> |
在 Web 项目中,通常会存在一些公共页面片段(重复代码),例如头部导航栏、侧边菜单栏和公共的 js css 等。我们一般会把这些公共页面片段抽取出来,存放在一个独立的页面中,然后再由其他页面根据需要进行引用,这样可以消除代码重复,使页面更加简洁。
Thymeleaf 作为一种优雅且高度可维护的模板引擎,同样支持公共页面的抽取和引用。我们可以将公共页面片段抽取出来,存放到一个独立的页面中,并使用 Thymeleaf 提供的 th:fragment 属性为这些抽取出来的公共页面片段命名。 示例 1 将公共页面片段抽取出来,存放在 commons.html 中,代码如下。
html<div th:fragment="fragment-name" id="fragment-id">
<span>公共页面片段</span>
</div>
在 Thymeleaf 中,我们可以使用以下 3 个属性,将公共页面片段引入到当前页面中。
使用上 3 个属性引入页面片段,都可以通过以下 2 种方式实现。
通常情况下,
{} 可以省略,其行内写法为 [[{...}]] 或 [({...})],其中 [[{...}]] 会转义特殊字符,[(~{...})] 则不会转义特殊字符。
示例 2
html<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name"></div>
<!--th:insert id 选择器引入-->
<div th:insert="commons::#fragment-id"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name"></div>
<!--th:replace id 选择器引入-->
<div th:replace="commons::#fragment-id"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name"></div>
<!--th:include id 选择器引入-->
<div th:include="commons::#fragment-id"></div>
html<!--th:insert 片段名引入-->
<div>
<div id="fragment-id">
<span>公共页面片段</span>
</div>
</div>
<!--th:insert id 选择器引入-->
<div>
<div id="fragment-id">
<span>公共页面片段</span>
</div>
</div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div id="fragment-id">
<span>公共页面片段</span>
</div>
<!--th:replace id 选择器引入-->
<div id="fragment-id">
<span>公共页面片段</span>
</div>
------------------------------------------------
<!--th:include 片段名引入-->
<div>
<span>公共页面片段</span>
</div>
<!--th:include id 选择器引入-->
<div>
<span>公共页面片段</span>
</div>
Thymeleaf 在抽取和引入公共页面片段时,还可以进行参数传递,大致步骤如下: 1.传入参数; 2.使用参数。
引用公共页面片段时,我们可以通过以下 2 种方式,将参数传入到被引用的页面片段中: 模板名::选择器名或片段名(参数1=参数值1,参数2=参数值2) 模板名::选择器名或片段名(参数值1,参数值2)
注:若传入参数较少时,一般采用第二种方式,直接将参数值传入页面片段中; 若参数较多时,建议使用第一种方式,明确指定参数名和参数值,。
示例代码如下:
java<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name(var1='insert-name',var2='insert-name2')"></div>
<!--th:insert id 选择器引入-->
<div th:insert="commons::#fragment-id(var1='insert-id',var2='insert-id2')"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name(var1='replace-name',var2='replace-name2')"></div>
<!--th:replace id 选择器引入-->
<div th:replace="commons::#fragment-id(var1='replace-id',var2='replace-id2')"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name(var1='include-name',var2='include-name2')"></div>
<!--th:include id 选择器引入-->
<div th:include="commons::#fragment-id(var1='include-id',var2='include-id2')"></div>
在声明页面片段时,我们可以在片段中声明并使用这些参数,例如:
java<!--使用 var1 和 var2 声明传入的参数,并在该片段中直接使用这些参数 -->
<div th:fragment="fragment-name(var1,var2)" id="fragment-id">
<p th:text="'参数1:'+${var1} + '-------------------参数2:' + ${var2}">...</p>
</div>
启动 Spring Boot,使用浏览器访问 fragment.html,结果如下图。
*请认真填写需求信息,我们会在24小时内与您取得联系。