thymeleaf教程

目录

thymeleaf的定义
spring boot整合
thymeleaf语法参考文档
thymeleaf笔记

thymeleaf比jsp好在哪
thymeleaf简单文件
thymeleaf配置 application.properties
thymeleaf url
thymeleaf表达式
themeleaf包含 footer
themeleaf条件 if
themeleaf 遍历
thymeleaf内置工具
thymeleaf分页

thymeleaf的定义

Thymeleaf是一种用于Web和独立环境的现代服务器端的Java模板引擎。主要目标是将优雅的自然模板带到开发工作流程中,并将HTML在浏览器中正确显示,并且可以作为静态原型,让开发团队能更容易地协作。Thymeleaf使用Spring框架的模块,与许多常见的工具集成在一起,并且可以插入自己的功能,能够处理HTML,XML,JavaScript,CSS,TEXT,RAW六种模板模式

spring boot整合

  1. 新建spring boot的web项目
    添加依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>

在spring boot是1.5.X时,thymeleaf依赖要用1.5.x版本,亲测用2版本会找不到网页。

  1. 将html网页放在templates文件夹下。
  2. controller即可跳转到html页面,页面路径为以templates为基础的相对路径。

thymeleaf语法参考文档

官方文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
目前网上教程不太多,https://www.yiibai.com/thymeleaf/standardurlsyntax.html 重点看标准方言。
目前比较浅显易懂的 http://how2j.cn/k/springboot/springboot-thymeleat/1735.html

thymeleaf笔记

thymeleaf比jsp好在哪

jsp要在服务器启动后转化为html页面。不启动服务器无法运行出结果。
thymeleaf服务器不启动他就已经是html。

thymeleaf简单文件

<html xmlns:th="http://www.thymeleaf.org">
<head>#内容与html无异
<p th:text="$name">name</p>
#服务器端未启动 显示name 启动显示服务器端传来的name值
#字符串拼接
<p th:text="|Hello! ${name}|"></p>

thymeleaf配置 application.properties

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false
#上下文 注意这里使得所有页面网址前缀都变为下述地址
server.context-path=/thymeleaf

thymeleaf url

引入css文件

<link rel="stylesheet" type="text/css" media="all" href="../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>

引入js文件

<script type="text/javascript" src="../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>

启动服务器后 th:src会代替src th:href会代替href

thymeleaf表达式

controller中添加属性

String htmlContent = "<p style='color:red'> 红色文字</p>";
m.addAttribute("htmlContent", htmlContent);
Product currentProduct =new Product(5,"product e", 200);
m.addAttribute("currentProduct", currentProduct);

转义与非转义

<p th:text="${htmlContent}" ></p>
<p th:utext="${htmlContent}" ></p>

效果


image.png

获取对象

方式1
<p th:text="${currentProduct}" ></p>
<p th:text="${currentProduct.name}" ></p>
<p th:text="${currentProduct.getName()}" ></p>
方式2
<div class="showing" th:object="${currentProduct}">
<h2>*{}方式显示属性</h2>
<p th:text="*{name}" ></p>
</div>

效果


image.png

此外还有算数运算

<p th:text="${currentProduct.price+999}" ></p>

themeleaf包含 footer

<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1"> 
   <p >All Rights Reserved</p>
</footer>
<footer th:fragment="footer2(start,now)"> 
   <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>

使用时按照

<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2015,2018)" ></div>

themeleaf条件if

<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句话就会显示</p>
<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句话就不会显示</p>
<p th:text="${testBoolean}?'当testBoolean为真的时候,显示本句话,这是用三相表达式做的':''" ></p>

不只是布尔值的 true 和 false, th:if 表达式返回其他值时也会被认为是 true 或 false,规则如下:

boolean 类型并且值是 true, 返回 true
数值类型并且值不是 0, 返回 true
字符类型(Char)并且值不是 0, 返回 true
String 类型并且值不是 "false", "off", "no", 返回 true
不是 boolean, 数值, 字符, String 的其他类型, 返回 true
值是 null, 返回 false

themeleaf 遍历

controller中

 List<Product> ps = new ArrayList<>();
        ps.add(new Product(1,"product a", 50));
        ps.add(new Product(2,"product b", 100));
        ps.add(new Product(3,"product c", 150));   
        m.addAttribute("ps", ps);

html中

 <table>
        <thead>
            <tr>
                <th>id</th>
                <th>产品名称</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="p: ${ps}">
                <td th:text="${p.id}"></td>
                <td th:text="${p.name}"></td>
                <td th:text="${p.price}"></td>
            </tr>
        </tbody>
    </table>

select与thymeleaf遍历结合

<div class="showing">
    <h2>遍历 select </h2>
    <select size="3">
        <option th:each="p:${ps}" th:value="${p.id}"     th:selected="${p.id==currentProduct.id}"    th:text="${p.name}" ></option>
    </select>
</div>
image.png

thymeleaf内置工具

#dates工具
now变量是controller中声明的Date now = new Date();

<div class="showing date">
    <h2>格式化日期</h2>
    直接输出日期 ${now}:
    <p th:text="${now}"></p>
    默认格式化 ${#dates.format(now)}:
    <p th:text="${#dates.format(now)}"></p>
    自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
    <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>
image.png

其他工具如

Execution Info
Messages
URIs/URLs
Conversions
Dates
Calendars
Numbers
Strings
Objects
Booleans
Arrays
Lists
Sets
Maps
Aggregates
IDs

手册见 http://how2j.cn/k/springboot/springboot-tool/1741.html#nowhere

thymeleaf分页

与数据库连接时的分页
pom加入

<!-- pageHelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

controller中示例

 @RequestMapping("/listCategory")
    public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start,size,"id desc");
        List<Category> cs=categoryMapper.findAll();
        PageInfo<Category> page = new PageInfo<>(cs);
        m.addAttribute("page", page);       
        return "listCategory";
    }

配置PageHelper

package com.how2java.springboot.config; 
import java.util.Properties; 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;  
import com.github.pagehelper.PageHelper;  
@Configuration
public class PageHelperConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}

html页面

 <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>编辑</td>
            <td>删除</td>
        </tr>
        <tr th:each="c:${page.list}">
            <td th:text="${c.id}"></td>
            <td th:text="${c.name}"></td>
            <td><a th:href="@{/editCategory(id=${c.id})}">编辑</a></td>
            <td><a th:href="@{/deleteCategory(id=${c.id})}">删除</a></td>
        </tr>
    </table>
    <br/>
    <div>
            <a th:href="@{/listCategory(start=0)}">[首  页]</a>
            <a th:href="@{/listCategory(start=${page.pageNum-1})}">[上一页]</a>
            <a th:href="@{/listCategory(start=${page.pageNum+1})}">[下一页]</a>
            <a th:href="@{/listCategory(start=${page.pages})}">[末  页]</a>
    </div>

效果


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容