本项目的笔记和资料的Download,请点击这一句话自行获取。css
day01-springboot(理论篇) ;day01-springboot(实践篇) ;day01-springboot(Thymeleaf快速入门)html
SpringBoot不推荐使用jsp,可是支持一些模板引擎技术:spring
简单说, Thymeleaf 是一个模板引擎,它能够彻底替代 JSP 。相较于其余的模板引擎,它有以下四个极吸引人的特色:浏览器
接下来,咱们就经过入门案例来体会Thymeleaf的魅力:缓存
编写一个controller方法,返回一些用户数据,放入模型中,未来在页面渲染springboot
@GetMapping("/all") public String all(ModelMap model) { // 查询用户 List<User> users = this.userService.queryAll(); // 放入模型 model.addAttribute("users", users); // 返回模板名称(就是classpath:/templates/目录下的html文件名) return "users"; }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
SpringBoot会自动为Thymeleaf注册一个视图解析器:服务器
与解析JSP的InternalViewResolver相似,Thymeleaf也会根据前缀和后缀来肯定模板文件的位置:网络
classpath:/templates/
.html
因此若是咱们返回视图:users
,会指向到 classpath:/templates/users.html
并发
通常咱们无需进行修改,默认便可。
根据上面的介绍,模板默认放在classpath下的templates文件夹,咱们新建一个html文件放入其中:
编写html模板,渲染模型中的数据:
注意,把html 的名称空间,改为:xmlns:th="http://www.thymeleaf.org"
会有语法提示。
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> <style type="text/css"> table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto} table, th, td {border: 1px solid darkslategray;padding: 10px} </style> </head> <body> <div style="text-align: center"> <span style="color: darkslategray; font-size: 30px">欢迎光临!</span> <hr/> <table class="list"> <tr> <th>id</th> <th>姓名</th> <th>用户名</th> <th>年龄</th> <th>性别</th> <th>生日</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}">1</td> <td th:text="${user.name}">张三</td> <td th:text="${user.userName}">zhangsan</td> <td th:text="${user.age}">20</td> <td th:text="${user.sex}">男</td> <td th:text="${user.birthday}">1980-02-30</td> </tr> </table> </div> </body> </html>
咱们看到这里使用了如下语法:
${}
:这个相似与el表达式,但实际上是ognl的语法,比el表达式更增强大th-
指令:th-
是利用了Html5中的自定义属性来实现的。若是不支持H5,能够用data-th-
来代替
th:each
:相似于c:foreach
遍历集合,可是语法更加简洁th:text
:声明标签中的文本
<td th-text='${user.id}'>1</td>
,若是user.id有值,会覆盖默认的1接下来,咱们打开页面测试一下:
Thymeleaf会在第一次对模板解析以后进行缓存,极大的提升了并发处理能力。可是这给咱们开发带来了不便,修改页面后并不会马上看到效果,咱们开发阶段能够关掉缓存使用:
# 开发阶段关闭thymeleaf的模板缓存
spring.thymeleaf.cache=false
在Idea中,咱们须要在修改页面后按快捷键:`Ctrl + Shift + F9` 对项目进行rebuild才能够。
============================
参考资料:
end