springboot_tymeleaf

依赖

< dependency>
< groupId>org.springframework.boot</ groupId>
< artifactId>spring-boot-starter-thymeleaf</ artifactId>
</

properties配置

#配置 Thymeleaf
#开发阶段设置为 false ,上线后设置为 true
spring.thymeleaf.cache=false
# 设置模版文件的路径,前缀
spring.thymeleaf.prefix=classpath:/templates/
# 设置后缀
spring.thymeleaf.suffix=.html
# 设置模版的类型
spring.thymeleaf.mode=HTML

表达式

标准变量表达式 ${key}

获取 Controller 中 model 其中的数据,也就是 request 作用域中的数据
tymeleaf 模板中接收值

<p th:text="${id}">id</p>
//接收对象中的变量
<p th:text="${user.Id}">id</p>

controller 中传值

model.addAttribute("id", "123");
model.addAttribute("myuser", new SysUser(1001, "李四", "m", 20));

选择变量表达式 *{key} 用于绑定对象,接收对象

tymeleaf 模板中接收值

<p>使用 *{} 获取SysUser的属性值</p>
        <div th:object="${myuser}">
            <p th:text="*{id}"></p>
            <p th:text="*{name}"></p>
            <p th:text="*{sex}"></p>
            <p th:text="*{age}"></p>
        </div>
        
使用*{}完成的表示 对象的属性值
        <p th:text="*{myuser.name}" ></p>

controller 中传值

model.addAttribute("myuser", new SysUser(1001, "李四", "m", 20));

链接表达式 @{链接 url}

说明:主要用于链接、地址的展示,可用于

    <h3>链接绝对路径</h3>
    <a th:href="@{http://www.baidu.com}">链接到百度</a>
    <h3>链接的是相对地址</h3>
    <a th:href="@{/tpl/queryAccount}">相对地址,没有参数</a>
    <h3>链接的相对地址,使用字符串链接向后端传递参数</h3>
    <a th:href="@{'/tpl/queryAccount?id='+ ${userId} }">获取model中数据</a>
    <h3>推荐使用的向后端传参数的方式</h3>
    <a th:href="@{/tpl/queryAccount(id=${userId})}">传参数</a>
    <h3>向后端传递多个参数</h3>
    <a th:href="@{/tpl/queryUser(name='lisi',age=20)}">传多个参数</a>
        

controller 中传值

//链接表达式
    @GetMapping("/link")
    public String link(Model model){
        model.addAttribute("userId",12022);
        return "link";
    }

    //测试链接表达式的地址,无参数接收
    @GetMapping("/queryAccount")
    @ResponseBody
    public String queryAccount(Integer id){
        System.out.println(id);
        return "queryAccount,参数id="+id;
    }


    //有两个参数的地址,接收数据
    @GetMapping("/queryUser")
    @ResponseBody
    public String queryUser(String name, Integer age){
        return "queryUser,有两个参数:name="+name+",age="+age;
    }

tymeleaf属性

大部分属性和 html 的一样,只不过前面加了一个 th 前缀。 加了 th 前缀的属性,就可以使用变量表达式

1. th:action

定义后台控制器的路径,类似标签的 action 属性,主要结合 URL 表达式,获取动态变量

<form id="login" th:action="@{/login}" th:method="post">......</form>

2. th:method

设置请求方法

<form th:action="@{/loginServlet}" th:method="${methodAttr}">

3. th:href

定义超链接,主要结合 URL 表达式,获取动态变量

<a th:href="@{/query/student}">相对地址没有传参数</a>

4. th:src

用于外部资源引入,比如

<script type="text/javascript" th:src="@{/js/jquery-3.4.1.js}"></script>

5. th:text

用于文本的显示,该属性显示的文本在标签体中,如果是文本框,数据会在文本框外显示,要想显示在文本框内,使用 th:value

<input type="text" id="realName" name="reaName" th:text="${realName}">

6. th:style

设置样式

<a th:onclick="'fun1('+${user.id}+')'" th:style="'color:red'">点击我</a>

7. th:each

这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与JSTL 中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map.

循环list
<tr th:each="user:${myusers}">
                 <td th:text="${userStat.count}+'/'+${userStat.size}"></td>
                 <td th:text="${user.id}"></td>
                 <td th:text="${user.name}"></td>
                 <td th:text="${user.sex}"></td>
                 <td th:text="${user.age}"></td>
                 <td th:text="${userStat.current.name}"></td>
                 <td th:text="${userStat.first}"/>
             </tr>

语法说明:
th:each=“user, iterStat : ${userlist}” 中的 u s e r L i s t 是 后 台 传 过 来 的 集 合 ◼ u s e r 定 义 变 量 , 去 接 收 遍 历 {userList} 是后台传过来的集合 ◼ user 定义变量,去接收遍历 userListuser{userList}集合中的一个数据
◼ iterStat
${userList} 循环体的信息
◼ 其中 user 及 iterStat 自己可以随便取名
◼ interStat 是循环体的信息,通过该变量可以获取如下信息
index: 当前迭代对象的 index (从 0 开始计算)
count: 当前迭代对象的个数(从 1 开始计算) 这两个用的较多
size: 被迭代对象的大小
current: 当前迭代变量
even/odd: 布尔值,当前循环是否是偶数/奇数(从 0 开始计算)
first: 布尔值,当前循环是否是第一个
last: 布尔值,当前循环是否是最后一个
息 注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即
userStat

循环数组
<div th:each="user:${userarray}">
          <p th:text="${user.id}"></p>
          <p th:text="${user.name}"></p>
          <p th:text="${user.sex}"></p>
          <p th:text="${user.age}"></p>
          <br/>
          <hr/>
      </div>
循环map
<div th:each="map,userStat:${mymap}">
            <p th:text="${map.key}"></p>
            <p th:text="${map.value}" ></p>
            <p th:text="${map.value.id}"></p>
            <p th:text="${map.value.name}"></p>
            <p th:text="${userStat.index}"></p>
            <br/>
            <hr/>
        </div>

条件判断 if

语法:th:if=”boolean 条件” , 条件为 true 显示体内容,th:unless 是 th:if 的一个相反操作

<p th:if="${sex=='m'}">性别是男</p>
<p th:unless="${sex=='f'}">性别是男的</p>

switch ,case 判断语句

语法:类似 java 中的 switch,case 用于显示或隐藏

<div th:switch="${sex}">
            <p th:case="f">性别是女</p>
            <p th:case="m">性别是男</p>
            <p th:case="*">未知</p>
        </div>

说明:一旦某个 case 判断值为 true ,剩的 余的 case 则都当做 false ,“* ”表示默认的
case ,前面的 case 都不匹配时候,执行默认的 case

内联 th:inline

th:inline 有三个取值类型 (text, javascript 和 none)

th:inline=“text”

<div th:inline="text">
            <p>我是[[${name}]],年龄是[[${age}]]</p>
            //上面代码等同于下面代码
            我是<span th:text="${name}"></span>,年龄是<span th:text="${age}"></span>
        </div>

th:inline=“javascript”

<script type="text/javascript" th:inline="javascript">
         var myname = [[${name}]];
         var myage = [[${age}]];

字面量

<h3>文本字面量: 使用单引号括起来的字符串,“数据显示”不使用</h3>
       <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>

       <h3>数字字面量</h3>
        <p th:if="${20>5}"> 20大于 5</p>

        <h3>boolean字面量</h3>
        <p th:if="${isLogin == true}">用户已经登录系统</p>

        <h3>null字面量</h3>
        <p th:if="${myuser != null}">有myuser数据</p>

字符串连接

		<h3>字符串连接方式1:使用单引号括起来的字符串</h3>
       <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>
       
        <h3>字符串连接方式2:|字符串和表达式|</h3>
        <p th:text="|我是${name},所在城市${city},其他人${myuser.name}|"></p>

运算符 作用是控制显示与否

算术运 算: + , - , * , / , %
关系比较 : > , < , >= , <= ( gt , lt , ge , le )
相等判断:== , != ( eq , ne )

<!--判断text="${age > 10}"结果显示true或false-->
        <p th:text="${age > 10}">年龄大于 10 </p>
        <p th:text="${ 20 + 30 }">显示运算结果</p>
        <p th:if="${myuser == null}">myuser是null</p>
        <p th:if="${myuser eq null}">myuser是null</p>
        <p th:if="${myuser ne null}">myuser不是null</p>
 		三元表达式
        <p th:text="${isLogin == true ? '用户已经登录' : '用户需要登录'}"></p>
        三元表达式嵌套
        <p th:text="${isLogin == true ? ( age > 10 ? '用户是大于10的' : '用户年龄比较小') : '用户需要登录'}"></p>

Thymeleaf 基本对象

模板引擎提供了一组内置的对象,这些内置的对象可以直接在模板中使用,这些对象由#号开始引用,我们比较常用的内置对象

#request 表示 HttpServletRequest

#session 表示 HttpSession 对象

session 对象,

表示 HttpSession session 表示Map对象的, 是#session的简单表示方式, 用来获取session中指定的key的值

param 参数对象

<p>获取作用域中的数据</p>
        <p th:text="${#request.getAttribute('requestData')}"></p>
        <p th:text="${#session.getAttribute('sessionData')}"></p>
        <p th:text="${session.loginname}"></p>
        <p th:text="${session.sessionData}"></p>

        <br/>
        <br/>
        <h3>使用内置对象的方法</h3>
        getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/>
        getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/>
        getQueryString=<span th:text="${#request.getQueryString()}"></span><br/>
        getContextPath=<span th:text="${#request.getContextPath()}"></span><br/>
        getServerName=<span th:text="${#request.getServerName()}"></span><br/>
        getServerPort=<span th:text="${#request.getServerPort()}"></span><br/>
        sessionId,getId=<span th:text="${#session.getId()}"></span>
        
<h3>param对象:表示请求的参数集合</h3>
        name参数的值:<span th:text="${param.name}"></span><br/>
        参数的数量:<span th:text="${param.size()}"></span><br/>

内置工具类

Thymeleaf自己的一些类,提供对string, date ,集合等的一些处理方法

#dates: 处理日器的工具类
#numbers:处理数字的
#lists: 处理list集合的

<h3>日期类对象 #dates</h3>
      <p th:text="${#dates.format(mydate )}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
      <p th:text="${#dates.year(mydate)}"></p>
      <p th:text="${#dates.month(mydate)}"></p>
      <p th:text="${#dates.monthName(mydate)}"></p>
      <p th:text="${#dates.createNow()}"></p>
      <br/>

      <h3>内置工具类#numbers,操作数字的</h3>
      <p th:text="${#numbers.formatCurrency(mynum)}"></p>
      <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>

      <br/>
      <h3>内置工具类#strings,操作字符串</h3>
      <p th:text="${#strings.toUpperCase(mystr)}"></p>
      <p th:text="${#strings.indexOf(mystr,'power')}"></p>
      <p th:text="${#strings.substring(mystr,2,5)}"></p>
      <p th:text="${#strings.substring(mystr,2)}"></p>
      <p th:text="${#strings.concat(mystr,'---java开发的黄埔军校---')}"></p>
      <p th:text="${#strings.length(mystr)}"></p>
      <p th:text="${#strings.length('hello')}"></p>
      <p th:unless="${#strings.isEmpty(mystr)}"> mystring 不是 空字符串  </p>

      <br/>
      <h3>内置工具类#lists,操作list集合</h3>
      <p th:text="${#lists.size(mylist)}"></p>
      <p th:if="${#lists.contains(mylist,'a')}">有成员a</p>
      <p th:if="!${#lists.isEmpty(mylist)}"> list 集合有多个成员</p>

      <br/>
      <h3>处理null</h3>
      zoo、dog加?表示zoo和dog自定义对象
      <p th:text="${zoo?.dog?.name}"></p>

补充:
#dates: java.util.Date 日期对象的实用方法,
#calendars: 和 dates 类似, 但是 java.util.Calendar 对象;
#numbers: 格式化数字对象的实用方法;
#strings: 字符串对象的实用方法: contains, startsWith, prepending/appending 等;
#objects: 对 objects 操作的实用方法;
#bools: 对布尔值求值的实用方法;
#arrays: 数组的实用方法;
#lists: list 的实用方法,比如
#sets: set 的实用方法;
#maps: map 的实用方法;
#aggregates: 对数组或集合创建聚合的实用方法

自定义模板

模板使用:

1.定义模板

2.使用模板

模板定义语法:

th:fragment="模板自定义名称"

例如:
<div th:fragment="head">
    <p>
        java开发
    </p>
    <p>
        www.baidu.com
    </p>
</div>

引用模板语法:

1) ~{templatename :: selector}
   templatename:  文件名称
   selector: 自定义模板名称
2)templatename :: selector
   templatename:  文件名称
   selector: 自定义模板名称

对于使用模板:有包含模板(th:include), 插入模板(th:insert)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值