themeleaf入门例子
JAVA 框架 / SPRINGBOOT / THYMELEAF 入门 基于 SPRINGBOOT 方式
Redis | URL |
相关下载 | |
---|---|
文件名 | 文件大小 |
thymeleaf.rar | 2k |
步骤 1 : 什么是 thymeleaf
步骤 2 : 先运行,看到效果,再学习
步骤 3 : 模仿和排错
步骤 4 : 基于前面的知识点
步骤 5 : pom.xml
步骤 6 : 增加个控制器
步骤 7 : hello.html
步骤 8 : application.properties
步骤 9 : 重启测试
步骤 1 :
什么是 thymeleaf
thymeleaf 跟 JSP 一样,就是运行之后,就得到纯 HTML了。 区别在与,不运行之前, thymeleaf 也是 纯 html ...
所以 thymeleaf 不需要 服务端的支持,就能够被以 html 的方式打开,这样就方便前端人员独立设计与调试, jsp 就不行了, 不启动服务器 jsp 都没法运行出结果来。
步骤 2 :
先运行,看到效果,再学习
顶折老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
运行 Application.java, 然后访问地址:
http://127.0.0.1:8080/thymeleaf/hello
就可以看到如图所示的三行话
步骤 3 :
模仿和排错
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。
推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 4 :
基于前面的知识点
thymeleaf 可以配合 Servlet 运行,但是比较常见的是配合 springboot 来运行。 当然本质上也是配合springboot 里的 springmvc 来运行的,毕竟 springboot 本身就是个老鸨,干活的还是 springmvc。
本知识点基于前面的 springboot 配置切换 的基础上展开。 所以如果没有学过 springboot, 还是把 springboot 过一遍的好,至少要过到 springboot 配置切换 这里。
步骤 5 :
pom.xml
顶折修改 pom.xml, 增加了对 thymeleaf 的支持。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</
</dependency>
代码比较复制代码
步骤 6 :
增加个控制器
很简单,访问地址 hello, 跳转到 hello.html ,并带上数据 "name", 其值是 "thymeleaf"
代码比较复制代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
步骤 7 :
hello.html
顶折在 resources 下新建目录 templates, 然后新建文件 hello.html
注: 并不是在 webapp下,这点和 jsp 不一样
hello.html 做了如下事情:
1. 声明当前文件是 thymeleaf, 里面可以用th开头的属性
<html xmlns:th="http://www.thymeleaf.org">
2. <head> 内容和普通 html 并无二致,略过
3. 把 name 的值显示在当前 p里,用的是th开头的属性: th:text, 而取值用的是 "${name}" 这种写法叫做 ognl,额。。。什么意思呢。。。就是跟EL表达式一样吧。 这样取出来放进p 里,从而替换到 原来p 标签里的 4个字符 "name" .
<p th:text="${name}" >name</p>
用这种方式,就可以把服务端的数据,显示在当前html里了。 重要的是: 这种写法是完全合法的 html 语法,所以可以直接通过浏览器打开 hello.html,也是可以看到效果的, 只不过看到的是 "name", 而不是 服务端传过来的值 "thymeleaf"。
4. 字符串拼写。 两种方式,一种是用加号,一种是在前后放上 ||, 显然第二种方式可读性更好。
<p th:text="'Hello! ' + ${name} + '!'" >hello world</p>
<p th:text="|Hello! ${name}!|" >hello world</p>
这两种方式都会得到: hello thymeleaf。
代码比较复制代码
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
步骤 8 :
application.properties
application.properties 撸成这样
代码比较复制代码
1 2 3 4 5 6 7 8 |
|
步骤 9 :
重启测试
顶折运行 Application.java, 然后访问地址:
http://127.0.0.1:8080/thymeleaf/hello
HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢