前言:
最近听说thymeleaf好像也挺流行的,还说是spring官方推荐使用,那thymeleaf究竟是什么呢?spring为什么推荐用它呢?怎么用呢?本文将为你揭秘!
一、thymeleaf简介:
thymeleaf是一种Java模板引擎,那何为模板引擎呢?模板引擎就是为了使用户页面和业务数据相互分离而出现的,将从后台返回的数据生成特定的格式的文档,这里说的特定格式一般都指HTML文档。它能够处理html、xml、js、css甚至纯文本,类似于freemarker。它的优点是语法优雅易懂、原型即页面、遵从web标准。原型即页面是它的特色,所谓原型即页面,就是你写的html,静态的去访问是什么样,动态的去访问还是这样,只不过动态的时候会把数据填充进去。
二、thymeleaf标准方言:
1、变量表达式:${...}
例如前端接收一个user,想取出user的name属性,就可以用变量表达式:
2、消息表达式:#{...}
也称为文本外部化、国际化或i18n.
...
3、选择表达式:*{...}
与变量表达式的区别:选择表达式是在当前选择的对象上执行而不是整个上下文。
这里id就用了选择表达式,在此处*{id}与${userModel.user.id}效果一样。
4、链接表达式:@{...}
url可以是相对的,也可以是绝对的。......
5、分段表达式:th:insert 、th:replace 、th:include
就相当插入。这三个的区别:
现有一个片段如下:
Hello Thymeleaf
#号分别代表insert、replace、include进行操作:
th:insert 的结果:
Hello Thymeleaf
把footer标签插入到了div标签中。
th:replace的结果:
Hello Thymeleaf
把div标签换成了footer标签。
th:include的结果:
Hello Thymeleaf
把div标签里面的内容换成了footer标签里面的内容。3.X版本后不再推荐使用。
6、字面量:
字面量可以是文本、数字、布尔和null等类型。
7、算术操作:+、-、*、/、%
例如:
8、其他运算符:
比较: >、=、<= (gt、lt、ge、le)
等价: ==、!= (eq、ne)
三目运算符:
9、迭代器:th:each
相当于Java的foreach.
这样就是遍历userList集合。
迭代器的状态变量有:
index、count、size、current、even/odd、first、last
10、条件语句:th:if、th:unless、switch
User is admin
User is guest
11、模板布局:th:fragment
比如定义一个公用的页头:
Thymeleaf in action
首页
在其他页面直接这样引用就行:
12、表达式基本对象:
表达式基本对象有:param、session、application、request、servletContext。
三、thymeleaf与springboot集成案例:
本案例使用gradle构建,未涉及数据库,数据保存在ConcurrentMap中。未曾了解gradle的老铁可以参考一下gradle的使用。点我下载本案例源码。
项目结构如下:
image.png
1、添加依赖:dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test') //thymeleaf的依赖
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
}
2、application.properties:#thymeleaf相关配置spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=falsespring.thymeleaf.mode=HTML5
3、entity层:public class User {
private Long id; private String name; private String email;
}
4、dao层:import java.util.ArrayList;import java.util.List;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.atomic.AtomicLong;import org.springframework.stereotype.Repository;import com.zhu.test.dao.UserDao;import com.zhu.test.entity.User;/**
* user dao层实现
* @author zhu
*
*/@Repositorypublic class UserDaoImpl implements UserDao { //用来计数的
private static AtomicLong counter = new AtomicLong(); // 用来保存user的map
private final ConcurrentMap userMap = new ConcurrentHashMap<>();
@Override
public User saveOrUpdateUser(User user) {
Long id = user.getId(); if(id == null) {//save
id = counter.incrementAndGet();
user.setId(id);
} this.userMap.put(id, user); return user;
} @Override
public void deleteUser(Long id) { this.userMap.remove(id);
} @Override
public User getUserById(Long id) { return this.userMap.get(id);
} @Override
public List listUsers() { return new ArrayList(this.userMap.values());
}
}
作者:贪挽懒月
链接:https://www.jianshu.com/p/7f370e01e055
打开App,阅读手记