SpringBoot ( 六 ) thymeleaf

3.thymeleaf

thymeleaf : 伴随 SpringBoot 流行开始流行的页面标签

3.0.准备

3.0.1.Maven导入依赖

在pom.xml 文件中增加thymeleaf的依赖

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

3.0.2.声明标签库

在index.html 页面的结点声明引入标签库

<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

在标签下的标签显示文本信息

<span th:text="'hello, thymeleaf ! '"></span> <br>

3.0.3.关闭缓存

在 项目的配置文件中默认是开启页面缓存, 修改配置为false

# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=false

3.0.4.创建测试用实体类

在这个测试类中包含多种常用的数据类型

package com.yuan.entity;

import lombok.Data;

import java.time.LocalDateTime;
import java.util.Date;

@Data
public class TestEntity {
    private Integer tid = 1;
    private String tname = "测试标题";
    private Date tdate = new Date();
    private LocalDateTime ttime = LocalDateTime.now();
    private String tsex = "1";
    private Integer tint = 15;
    private Double tdou = 123.4567;
    private String tinfo = "这是一段测试文字, 可能会很长. 在很久久以后, 第三次文明纪元开始没多久, 掌握了文明的新人类发现了旧文明纪元时代的上古遗迹.";
    private String thtml = "<span style='color:red;' ><b>这是一段html代码</b></span>";
    private String tnull;
    private Boolean tbool = true;
}

3.1.基本表达式

3.1.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test01方法

index.html

    <a th:href="@{/test01}">test01 基本表达式</a> <br/>

在 Controller 中添加方法

通过 ModelMap, 传递 实体类, 字符串两组信息到 test 01.html页面

package com.yuan.controller;

import com.yuan.entity.TestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TagController {


    @RequestMapping("test01")
    public String test01(ModelMap modelMap){
        TestEntity testEntity = new TestEntity();
        modelMap.put("entity", testEntity);
        modelMap.put("data", "hello test01");
        return "test01";
    }
}

3.1.2.接收数据

在 templates文件夹下增加test01.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
字符串拼接1: <span th:text="'Welcome , ' + ${entity.tname} + '!'"></span> <br/>
字符串拼接2: <span th:text="${'Welcome , ' + entity.tname + '!'}"></span> <br/>
字符串拼接3: <span th:text="|Welcome , ${entity.tname}!|"></span> <br/>
直接取值: <span th:text="${data}" >测试标题</span>   <br/>
html输出: <span th:utext="${entity.thtml}" >测试标题</span>   <br/>
取对象属性值: <span th:text="${entity.tname}" >tname</span>  <br/>
直接取值: <input type="text"  value="hw" th:value="${data}" />  <br/>
取对象属性值: <input type="text" name="tname" value="tname" th:value="${entity.tname}" />  <br/>
对象取值: <div th:object="${entity}">
            tname: <span th:text="*{tname}">tname</span> <br>
            tint: <span th:text="*{tint}">tint</span> <br>
         </div>
</body>
</html>
3.1.2.1.取值${}

使用 ${} 可以从作用域里取值 ,

使用 ${} 的HTML属性名前加 th:

3.1.2.2.从对象里取值
  1. 通过 对象.属性 形式, 从对象取属性的值

    html输出: <span th:utext="${entity.thtml}" >测试标题</span>   <br/>
    取对象属性值: <span th:text="${entity.tname}" >tname</span>  <br/>
    取对象属性值: <input type="text" name="tname" value="tname" th:value="${entity.tname}" />  <br/>
    
  2. 可以使用 th:object*{} 嵌套的方式 从对象取属性对应的值

    对象取值: <div th:object="${entity}">
                tname: <span th:text="*{tname}">tname</span> <br>
                tint: <span th:text="*{tint}">tint</span> <br>
             </div>
    
3.1.2.3.显示位置

th:value 显示在 value属性的位置

直接取值: <input type="text"  value="hw" th:value="${data}" />  <br/>
取对象属性值: <input type="text" name="tname" value="tname" th:value="${entity.tname}" />  <br/>

th:text 显示在标签首尾之间的文本信息

直接取值: <span th:text="${data}" >测试标题</span>   <br/>
取对象属性值: <span th:text="${entity.tname}" >tname</span>  <br/>

th:utext 显示在标签首尾之间的HTML信息

html输出: <span th:utext="${entity.thtml}" >测试标题</span>   <br/>
3.1.2.4.信息连接

多个信息 连接在一起显示, 有多种结构

字符串拼接1: <span th:text="'Welcome , ' + ${entity.tname} + '!'"></span> <br/>
字符串拼接2: <span th:text="${'Welcome , ' + entity.tname + '!'}"></span> <br/>
字符串拼接3: <span th:text="|Welcome , ${entity.tname}!|"></span> <br/>

3.2.内置对象

3.2.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test02方法

index.html

    <a th:href="@{/test02}">test02 内置对象</a> <br/>

在 Controller 中添加方法

通过 ModelMap, HttpSession 封装数据, 传递 到 test 02.html页面

    @RequestMapping("test02")
    public String test02(HttpSession session, ModelMap modelMap){
        TestEntity entity = new TestEntity();
        // 封装数据到 request容器
        modelMap.put("mstr", "hello request");

        // 封装数据到 session容器
        session.setAttribute("sdata", entity);
        session.setAttribute("sstr", "hello session");
        
        return "test02";
    }

3.2.2.接收数据

在 templates文件夹下增加test02.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<span th:text="${#request.getAttribute('mstr')}"></span> <br>
<hr/>
<span th:text="${#session.getAttribute('sstr')}"></span> <br>
<span th:text="${#session.getAttribute('sdata')}"></span> <br>
<hr/>
<span th:text="${session.sdata.tname}"></span> <br>

</body>
</html>
3.2.2.1.内置对象

${#ctx} : 上下文对象,可用于获取其它内置对象。
${#vars} : 上下文变量。
${#locale}:上下文区域设置。
${#request}: HttpServletRequest对象。
${#response}: HttpServletResponse对象。
${#session}: HttpSession对象。
${#servletContext}: ServletContext对象。

3.2.2.2.request

从request作用域取出封装在ModelMap里的数据

<span th:text="${#request.getAttribute('mstr')}"></span> <br>
3.2.2.3.session

#session表示HttpSession对象

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

<span th:text="${#session.getAttribute('sstr')}"></span> <br>
<span th:text="${#session.getAttribute('sdata')}"></span> <br>
<hr/>
<span th:text="${session.sdata.tname}"></span> <br>

3.3.内置工具类对象

3.3.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test03方法

index.html

    <a th:href="@{/test03}">test03 内置工具类对象</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装String , double, boolean, Array , List , Map , Date数据, 传递 到 test 03.html页面

    @RequestMapping("test03")
    public String test03(ModelMap modelMap){

        modelMap.put("testStr", "hello String");
        modelMap.put("testNum", 8888.888);
        modelMap.put("testBool", true);
        modelMap.put("testArray", new Integer[]{1,2,3,4});
        modelMap.put("testList", Arrays.asList(1,3,2,4,0));
        Map testMap = new HashMap();
        testMap.put("tmtitle", "标题");
        testMap.put("tmdesc", "说明说明说明说明说明");
        modelMap.put("testMap", testMap);
        modelMap.put("testDate", new Date());
        return "test03";
    }

3.3.2.接收数据

在 templates文件夹下增加test03.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h2>Thymeleaf 内置工具类对象</h2>
<h3>#strings :  <span th:text="${testStr}"/> </h3>
<div th:if="${not #strings.isEmpty(testStr)}" >
	<p>获取长度 length : <span th:text="${#strings.length(testStr)}"/></p>
    <p>判断是否为空 isEmpty : <span th:text="${#strings.isEmpty(testStr)}"/></p>
    <p>判断是否为非空 not : <span th:text="${not #strings.isEmpty(testStr)}"/></p>
    <p>转大写 toUpperCase : <span th:text="${#strings.toUpperCase(testStr)}"/></p>
    <p>转小写 toLowerCase : <span th:text="${#strings.toLowerCase(testStr)}"/></p>
    <p>判断相等(区分大小写) equals : <span th:text="${#strings.equals(testStr, 'hello string')}"/></p>
    <p>判断相等(不区分大小写) equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(testStr, 'hello string')}"/></p>
    <p>寻址 indexOf : <span th:text="${#strings.indexOf(testStr, 'rr')}"/></p>
    <p>截取 substring : <span th:text="${#strings.substring(testStr, 2, 8)}"/></p>
    <p>替换 replace : <span th:text="${#strings.replace(testStr, 'll', 'TT')}"/></p>
    <p>以xxx开头 startsWith : <span th:text="${#strings.startsWith(testStr, 'he')}"/></p>
    <p>包含 contains : <span th:text="${#strings.contains(testStr, 'll')}"/></p>
</div>

<h3>#numbers :  <span th:text="${testNum}"/>  </h3>
<div>
    <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(testNum, 0, 2)}"/></p>
    <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(testNum, 5, 2)}"/></p>
  	<p>formatDecimal 整数部分保留,按千位,分隔: <span th:text="${#numbers.formatDecimal(testNum, 0, 'COMMA', 2, 'POINT')}"/></p>
</div>

<h3>#bools :  <span th:text="${testBool}"/>  </h3>
<div th:if="${#bools.isTrue(testBool)}">
    <p >是否为true isTrue : <span th:text="${#bools.isTrue(testBool)}" ></span></p>
</div>

<h3>#arrays  :  <span th:text="${'1,2,3,4'}"/>  </h3>
<div th:if="${not #arrays.isEmpty(testArray)}">
    <p>长度 length : <span th:text="${#arrays.length(testArray)}"/></p>
    <p>包含 contains : <span th:text="${#arrays.contains(testArray, 15)}"/></p>
    <p>全包含 containsAll : <span th:text="${#arrays.containsAll(testArray, testArray)}"/></p>
</div>
<h3>#lists  :  <span th:text="${'1,3,2,4,0'}"/>  </h3>
<div th:if="${not #lists.isEmpty(testList)}">
    <p>长度 size : <span th:text="${#lists.size(testList)}"/></p>
    <p>包含 contains : <span th:text="${#lists.contains(testList, 0)}"/></p>
    <p>排序 sort : <span th:text="${#lists.sort(testList)}"/></p>
</div>
<h3>#maps  :  <span th:text="${testMap}"/>  </h3>
<div th:if="${not #maps.isEmpty(testMap)}">
    <p>长度 size : <span th:text="${#maps.size(testMap)}"/></p>
    <p>包含key containsKey : <span th:text="${#maps.containsKey(testMap, 'tmtitle')}"/></p>
    <p>包含value containsValue : <span th:text="${#maps.containsValue(testMap, '说明')}"/></p>
</div>
<h3>#dates :  <span th:text="${testDate}"/>   </h3>
<div>
    <p>默认格式输出 format : <span th:text="${#dates.format(testDate)}"/></p>
    <p>指定格式输出 custom format : <span th:text="${#dates.format(testDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
    <p>日 day : <span th:text="${#dates.day(testDate)}"/></p>
    <p>月 month : <span th:text="${#dates.month(testDate)}"/></p>
    <p>月名 monthName : <span th:text="${#dates.monthName(testDate)}"/></p>
    <p>年 year : <span th:text="${#dates.year(testDate)}"/></p>
    <p>星期 dayOfWeekName : <span th:text="${#dates.dayOfWeekName(testDate)}"/></p>
    <p>时 hour : <span th:text="${#dates.hour(testDate)}"/></p>
    <p>分 minute : <span th:text="${#dates.minute(testDate)}"/></p>
    <p>秒 second : <span th:text="${#dates.second(testDate)}"/></p>
    <p>当前时间 createNow : <span th:text="${#dates.createNow()}"/></p>
</div>


</body>
</html>

3.4.流程结构

3.4.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test04方法

index.html

    <a th:href="@{/test04}">test04 流程结构</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装对象, List等数据, 传递 到 test 04.html页面

    @RequestMapping("test04")
    public String test04(ModelMap modelMap){
        // 在ModelMap中存入对象
        TestEntity entity = new TestEntity();
        //entity.setTinfo("");
        //entity.setTinfo(null);
        modelMap.put("entity", entity);

        // 在ModelMap中存入List
        List<TestEntity> list = getTestEntityList();
        modelMap.put("list", list);


        return "test04";
    }

    private List<TestEntity> getTestEntityList() {
        List<TestEntity> list = new ArrayList<>();
        TestEntity te1 = new TestEntity();
        te1.setTid(1);
        te1.setTname("王小二");
        te1.setTsex("1");
        te1.setTtime(LocalDateTime.now());
        System.out.println("te1 = " + te1);
        list.add(te1);

        TestEntity te2 = new TestEntity();
        te2.setTid(2);
        te2.setTname("李小三");
        te2.setTsex("0");
        te2.setTtime(LocalDateTime.now());
        System.out.println("te2 = " + te2);
        list.add(te2);

        TestEntity te3 = new TestEntity();
        te3.setTid(3);
        te3.setTname("赵小四");
        te3.setTsex("1");
        te3.setTtime(LocalDateTime.now());
        System.out.println("te3 = " + te3);
        list.add(te3);
        return list;
    }

3.4.2.接收数据

在 templates文件夹下增加test03.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
----------------if-----------------<br>
<input th:style="${entity.tsex eq '1'} ? 'color:red;'"  th:value="${entity.tint}" /><br>
(与5比较)
<span th:if="${entity.tint lt 5}"   th:text="${'小于 5'}" >123</span>
<span th:if="${entity.tint gt 5}"   th:text="${'大于 5'}" >123</span> <br/>

<span th:text="${'tnull = ' + entity.tnull }"></span>
<span th:if="${entity.tnull} eq '' "   th:text="${' : 与 \'\'比较'}" >123</span>
<span th:if="${entity.tnull} eq null "   th:text="${' : 与 null 比较'}" >123</span> <br/>
   
<span  th:if="${entity.tinfo} eq '' or  ${entity.tinfo} eq null "  th:text="没有说明信息" /> <br/>
<span  th:if="${entity.tinfo} ne '' and  ${entity.tinfo} ne null "  th:text="${entity.tinfo}" /> <br/>
----------------unless-- 和th:if判断相反  ---------------<br>
<input type="text" th:value="${entity.tname}"  th:unless="${entity.tname} eq null"  /> <br/>
<input type="text" th:value="${entity.tname}"  th:if="${ not (entity.tname eq null)}"  /> <br/>
----------------switch-----------------<br>
<div th:switch="${entity.tsex}">
    <span  th:case="'1'"></span>
    <span  th:case="'0'"></span>
</div>
    

----------------each  table -----------------<br>
<table border="1"  width="500" >
    <tbody th:remove="all-but-first">         
    <tr th:each="row,i:${list}" >
<!--        <td th:text="${rowStat.count}">1</td>-->
        <td th:text="${i.count}">1</td>
        <td th:text="${row.tname}">Red Chair</td>
        <td th:text="${row.tsex}">1</td>
        <td th:text="${row.tsex eq '1'?'':''}">1</td>
        <td th:switch="${row.tsex}">
            <span  th:case="'1'"></span>
            <span  th:case="'0'"></span>
        </td>
        <td th:text="${#temporals.format(row.ttime,'yyyy-MM-dd HH:mm:ss')}">2014-12-01</td>
    </tr>
    <tr>
        <td>White table</td>
        <td>$200</td>
        <td>15-Jul-2013</td>
    </tr>
    <tr>
        <td>Reb table</td>
        <td>$200</td>
        <td>15-Jul-2013</td>
    </tr>
    <tr>
        <td>Blue table</td>
        <td>$200</td>
        <td>15-Jul-2013</td>
    </tr>
    </tbody>
</table>
   <br>
<table  border="1"  width="500" >
    <th:block th:each="te : ${list}">
        <tr>
            <td th:text="${te.tid}">...</td>
            <td th:text="${te.tname}">...</td>
        </tr>
        <tr>
            <td colspan="2" th:text="${te.tinfo}">...</td>
        </tr>
    </th:block>
</table>
----------------each select-----------------<br>
<select   th:value="${id}"  >
    <option value="">~请选择~</option>
    <option th:each="t:${list}"  th:value="${t.tid }" th:text="${t.tname}"  >请选择</option>
</select>
<br>
----------------each  input-----------------<br>

<input type ="checkbox" name="arr"
       th:each ="t:${list}"
       th:value="${t.tid }" th:text="${t.tname}" >

</body>
</html>
3.4.2.1.比较 if

th:if 用于判断

>、<、>=、<=、==、!=lt、gt、le、ge、eq、ne 作用相同

<span th:if="${entity.tint lt 5}"   th:text="${'小于 5'}" >123</span>
<span th:if="${entity.tint gt 5}"   th:text="${'大于 5'}" >123</span> <br/>

与 String字符串类型比较时 要加 '单引号'

<input th:style="${entity.tsex eq '1'} ? 'color:red;'"  th:value="${entity.tint}" /><br>

<div th:switch="${entity.tsex}">
    <span  th:case="'1'"></span>
    <span  th:case="'0'"></span>
</div>

多个判断条件使用 or 或者 and 连接

<span  th:if="${entity.tinfo} eq '' or  ${entity.tinfo} eq null "  th:text="没有说明信息" /> <br/>
<span  th:if="${entity.tinfo} ne '' and  ${entity.tinfo} ne null "  th:text="${entity.tinfo}" /> <br/>
3.4.2.2.unless

th:unless 作用与 th:if 相反 , 相当于 在if 的判断前 加 not

<input type="text" th:value="${entity.tname}"  th:unless="${entity.tname} eq null"  /> <br/>
<input type="text" th:value="${entity.tname}"  th:if="${ not (entity.tname eq null)}"  /> <br/>
3.4.2.3.循环 each

th:each 用于循环集合 , 是写在 重复生成元素标签上

​ 值的写法类似于 增强for循环 , 使用 : 分成两个部分 ,

​ 右边使用${} 取集合的值 , 左边通过 , 连接 集合元素的别名及循环序号

​ 这个循环序号是个对象, 要调用对应属性得到值, 如本例 : 循环序号起名 i , 序号值 i.count

​ 也可以省略这个循环序号 , 默认以别名 + stat 为它起名, 如本例 : 如果没有定义为 i , 而循环元素别名为 row, 则循环序号默认为 rowStat

 <tr th:each="row,i:${list}" >
<!--        <td th:text="${rowStat.count}">1</td>-->
     <td th:text="${i.count}">1</td>
     <td th:text="${row.tname}">Red Chair</td>
     <td th:text="${row.tsex}">1</td>
     <td th:text="${row.tsex eq '1'?'':''}">1</td>
     <td th:switch="${row.tsex}">
         <span  th:case="'1'"></span>
         <span  th:case="'0'"></span>
     </td>
     <td th:text="${#temporals.format(row.ttime,'yyyy-MM-dd HH:mm:ss')}">2014-12-01</td>
     <td th:text="${#dates.format(row.tdate,'yyyy-MM-dd HH:mm:ss')}">2014-12-01</td>
</tr>
3.4.2.4.删除元素

th:remove 删除元素, 要用在有子元素的元素标签上

​ 当值为 all-but-first 表示除了第一个子元素以外的子元素

 <tbody th:remove="all-but-first">   

删除可选择值

  1. all : 删除包含标签和所有的孩子
  2. body : 不包含标记删除,但删除其所有的孩子
  3. tag : 包含标记的删除,但不删除它的孩子
  4. all-but-first : 删除所有包含标签的孩子,除了第一个
  5. none : 什么也不做。这个值是有用的动态评估。
3.4.2.5.th:block

创建区域块(内容为空则不创建),之后th:block标签消失

使用table输出内容时,每次输出以两行为一个单位

<table  border="1"  width="500" >
    <th:block th:each="te : ${list}">
        <tr>
            <td th:text="${te.tid}">...</td>
            <td th:text="${te.tname}">...</td>
        </tr>
        <tr>
            <td colspan="2" th:text="${te.tinfo}">...</td>
        </tr>
    </th:block>
</table>

3.5.form表单回显

3.5.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test05方法

index.html

    <a th:href="@{/test05}">test05 form表单</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装对象, List等数据, 传递 到 test 03.html页面

    @RequestMapping("test05")
    public String test05( ModelMap modelMap){
        TestEntity entity = new TestEntity();
        modelMap.put("entity", entity);

        List<TestEntity> list = getTestEntityList();
        modelMap.put("list", list);
        
                // 为复选框赋值
        TestPage tp = new TestPage();
        tp.setArr(new Integer[]{1,3});
        modelMap.put("tp", tp);

        return "test05";
    }


    @RequestMapping("testParam")
    @ResponseBody
    public void testParam(TestEntity entity, Integer[] arr){
        System.out.println("entity = " + entity);
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
    }
3.5.1.1.增加TestPage
package com.yuan.entity;

import lombok.Data;

@Data
public class TestPage {

    private Integer[] arr ;

}

3.5.2.接收数据

在 templates文件夹下增加test05.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/testParam}" th:object="${entity}"  method="post"  th:method="post">

    <input type="text"  th:field="*{tid}"    value="tid" /> <br/>
    <input type="text"  th:field="*{tname}"  value="tname" /> <br/>
    <input type="text"  th:field="*{tint}"  value="tint" /> <br/><br/>

    <select     th:field="*{tid}" >
        <option value="">请选择</option>
        <option th:each="t:${list}"  th:value="${t.tid }" th:text="${t.tname}"  >请选择</option>
    </select>
    <br/><br/>
    <input type="text"  th:field="*{tsex}"  value="tsex" /> <br/>
    <input type="radio"  th:field="*{tsex}"   th:value="0"  th:checked="checked"   value="0" /><input type="radio"  th:field="*{tsex}"   th:value="1"  th:checked="checked"   value="1" /><br/><br/>
    <input type="date"   th:value="*{#dates.format(tdate, 'yyyy-MM-dd')}"  value="2014-12-01" /> <br/>
    
    <br/>
        <input type ="checkbox" name="arr"
           th:each ="t:${list}"
           th:value="${t.tid }" th:text="${t.tname}"

           th:attr ="checked=${#arrays.contains(tp.arr, t.tid)?true:false}" >
    <br/>
    <input type="submit" value="提交"/>
</form>
<hr>
<input type="date" name="tdate"  th:value="${#dates.format(entity.tdate, 'yyyy-MM-dd')}"  value="2014-12-01" /><br/>
<input type="text" name="tdou"  th:value="${#numbers.formatDecimal(entity.tdou, 1, 2)}"   /> <br/>
<input type="text" name="tinfo" th:value="${#strings.substring(entity.tinfo,0,5) + '...'}"      value="tinfo" /> <br/>

</body>
</html>
3.5.2.1.th:value

通过为 th:value 赋值 实现回显

3.5.2.2.th:field

th:field 在form表单中 实现回显

 <input type="text"  th:field="${entity.tname}"  value="tname" /> <br/>

th:field 被 解析后, 同时 生成 name, id, value 三个属性, 查看源代码得到

  <input type="text"  value="测试标题" id="tname" name="tname" /> <br/>
3.5.2.3.*{}

th:fieldth:object 配合使用时 , 使用 *{} 进行取值

<form th:action="@{/test05}" th:object="${entity}"  method="post"  th:method="post">

    <input type="text"  th:field="*{tid}"    value="tid" /> <br/>
3.5.2.4.th:attr

th:attr 为指定的属性赋值

本例 : 复选框 默认选中 使用 checked=true , th:attr 结合 内置工具类对象 #arrays进行判断

​ 传来的 tp.arr 集合是否包含当前的 t 的 tid 值

th:attr ="checked=${#arrays.contains(tp.arr, t.tid)?true:false}"

3.6.JS接值

3.6.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test06方法

index.html

 <a th:href="@{/test06}">test06 JS使用</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装对象, List等数据, 传递 到 test 06.html页面

    @RequestMapping("test06")
    public String test06(ModelMap modelMap){
        TestEntity entity = new TestEntity();
        modelMap.put("entity", entity);
        return "test06";
    }

3.6.2.接收数据

在 templates文件夹下增加test06.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<button type="button"   th:onclick="fn([[${entity.tname}]], [[${entity.tsex}]])" >点我</button>

<p>Hello, [[${entity.tname}]]!</p>

</body>
<script type="text/javascript"  th:inline="javascript" >
    var name = '[[${entity.tname}]]'
    console.log(name);
    var tint = [[${entity.tint}]]
    console.log(tint);

    function fn(name, sex){
        console.log(name + "->" + sex);
    }

</script>
</html>
3.6.2.1.[[]]接值

[[${}]] 使用这种结构在JS中接收值

3.7.定位资源

3.7.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test07方法

index.html

    <a th:href="@{/test07}">test07 导入资源</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装对象数据, 传递 到 test07.html页面

    @RequestMapping("test07")
    public String test07(ModelMap modelMap){
        TestEntity entity = new TestEntity();
        modelMap.put("entity", entity);
        return "test07";
    }

3.7.2.接收数据

在 templates文件夹下增加test07.html接收数据

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/c1.css}"/>
    <script type="text/javascript"  th:src="@{/js/j1.js}" src="js/j1.js"></script>
</head>
<body>

样式测试: <input th:value="${entity.tname}"> <br>

<hr>
<img th:src="@{/img/logo.png}">
<hr>

<a th:href="@{/testParam}">@{/testParam}</a>
两种作用相同
<a href="/testParam">/testParam</a>  <br/>

<a href="result.html" th:href="@{'/testParam?tid=' + ${entity.tid} }" >request Controller url?</a>
两种作用相同
<a href="result.html" th:href="@{/testParam(tid=${entity.tid})}" >request Controller ()</a> <br/>

<a th:href="@{/testParam(tid=3,tname='namestring')}">多参数</a><br/>

<a th:href="@{http://www.baidu.com}" >baidu</a>
两种作用相同
<a href="http://www.baidu.com">baidu</a> <br/>
<hr/>
</body>
</html>
3.7.2.1.@{} 定位符

@{} 导入JS, CSS, image 等资源可以使用@{}

    <link rel="stylesheet" type="text/css" th:href="@{/css/c1.css}"/>
    <script type="text/javascript"  th:src="@{/js/j1.js}" src="js/j1.js"></script>
    <img th:src="@{/img/logo.png}">

@{} 后面的路径与实际文件路径要对应

这些文件通常都放置在 static文件夹中, 因为这些文件通常在项目运行期是不会变化的, 所以都是静态资源

3.7.2.2.请求

在请求时使用@{} 包裹 URL路径 与 之间写URL路径效果一样

<a th:href="@{/testParam}">@{/testParam}</a>
两种作用相同
<a href="/testParam">/testParam</a>  <br/>
3.7.2.3.请求时传参

可以使用URL?传参, 与可以写在(小括号) 里传参

<a href="result.html" th:href="@{'/testParam?tid=' + ${entity.tid} }" >request Controller url?</a>
两种作用相同
<a href="result.html" th:href="@{/testParam(tid=${entity.tid})}" >request Controller ()</a> <br/>

<a th:href="@{/testParam(tid=3,tname='namestring')}">多参数</a><br/>
3.7.2.4.请求网络资源

要写完整的URL

<a th:href="@{http://www.baidu.com}" >baidu</a>
两种作用相同
<a href="http://www.baidu.com">baidu</a> <br/>

3.8.引入信息

3.8.1.提供数据

在 index.html页面, 添加超链接请求Controller中的test08方法

index.html

    <a th:href="@{/test08}">test08 引入信息</a> <br/>

在 Controller 中添加方法

通过 ModelMap 封装对象数据, 传递 到 test07.html页面

    @RequestMapping("test08")
    public String test08(){

        return "test/test08";
    }

3.8.2.接收数据

在 templates文件夹下增加 test/test08.html 接收数据

<!DOCTYPE html>
<html lang="en"  xmlns="http://www.w3.org/1999/xhtml"    xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <include th:replace="common/header" />
</head>
<body>
    <input value="测试信息">
</body>
<div th:include="/common/footer :: jscode(msg='hello')"></div>
</html>

在 templates文件夹下增加 common/header.html 接收数据

    <style type="text/css">
        input{
            width:200px;
            font-family: 微软雅黑;
            color: red;
            background: yellow;
        }
        button{
            color:blue;
            background: burlywood;
        }
    </style>

在 templates文件夹下增加 common/footer.html 接收数据

<div th:fragment="jscode(msg)">
    <button  th:onclick="sayHello()">按钮</button>

    <script type="text/javascript" th:inline="javascript">
        function sayHello(){
            console.log([[${msg}]])
        }
    </script>
</div>
3.8.2.1.导入信息

th:include 和 th:replace都是加载代码块内容,但是还是有所不同

th:include:加载模板的内容: 读取加载节点的内容(不含节点名称),替换div内容
th:replace:替换当前标签为模板中的标签,加载的节点会整个替换掉加载他的div

公共部分如下:

<!-- th:fragment 定义用于加载的块 -->
<span th:fragment="pagination"> 
the public pagination
</span>

引用时如下:

================= th:include 和 th:replace============================
<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的内容 -->
<div th:include="pagination::pagination">1</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载他的<div>  -->
<div th:replace="pagination::pagination">2</div>

结果如下:

<!-- 加载模板的内容: 读取加载节点的内容(不含节点名称),替换<div>的内容 -->
<div> the public pagination</div>
<!-- 替换当前标签为模板中的标签: 加载的节点会整个替换掉加载他的<div>  -->
<span> the public pagination</span>
3.8.2.2.路径与函数

:: 连接 , 左边是 路径/文件名 , 右边是 th:fragment 定义的函数

函数参数使用 参数名=参数值 形式赋值

<div th:include="/common/footer :: jscode(msg='hello')"></div>

空标签

th:block  
关键字功能介绍案例
th:id替换id
th:text文本替换

description

th:utext支持html的文本替换

conten

th:object替换对象
th:value属性赋值
th:with变量赋值运算
th:style设置样式(不好使)th:style=“‘display:’ + @{(${sitrue} ? ‘none’ : ‘inline-block’)} + ‘’”
th:onclick点击事件th:οnclick=“‘getCollect()’”
th:each属性赋值tr th:each=“user,userStat:${users}”
th:if判断条件
th:unless和th:if判断相反<a th:href=“@{/login}” th:unless=${session.user != null}>Login
th:href链接地址<a th:href=“@{/login}” th:unless=${session.user != null}>Login
th:switch多路选择 配合th:case 使用
th:caseth:switch的一个分支

User is an administrator

th:fragment布局标签,定义一个代码片段,方便其它地方引用
th:include布局标签,替换内容到引入的文件
th:replace布局标签,替换整个标签到引入的文件
th:selectedselected选择框 选中th:selected=“(${xxx.id} == ${configObj.dd})”
th:src图片类地址引入App Logo
th:inline定义js脚本可以使用变量
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: springboot+thymeleaf项目是一种基于Java语言开发的Web应用程序。它采用了Spring Boot框架和Thymeleaf模板引擎,可以快速地搭建一个高效、可靠、易于维护的Web应用程序。该项目具有以下特点: 1. 简单易用:Spring Boot框架提供了一系列的自动化配置,使得开发者可以快速地搭建一个Web应用程序,而不需要过多的配置。 2. 高效可靠:Spring Boot框架采用了一系列的优化措施,使得应用程序具有高效、可靠的性能。 3. 易于维护:Thymeleaf模板引擎提供了一种简单、易于维护的模板语言,使得开发者可以快速地开发出具有良好可读性的Web应用程序。 总之,springboot+thymeleaf项目是一种非常优秀的Web应用程序开发框架,可以帮助开发者快速地开发出高效、可靠、易于维护的Web应用程序。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发框架,这个框架的优点在于其简单易用,能够快速搭建一个Java Web应用程序,无需进行复杂的配置和繁琐的XML文件编写。而Thymeleaf则是一种Web和HTML的模板引擎,可以方便地处理文本、链接和表单等元素,支持多重继承和页面片段的复用等特性。 Spring BootThymeleaf的结合,可以帮助开发人员更加简便地搭建Web应用程序。在使用Spring Boot进行项目开发时,可以使用Thymeleaf来完成Web开发的视图层,进行模版板的渲染和数据绑定。这样就可以很直接地将数据通过模板引擎展现出来,且更加方便。 在一个Spring Boot Thymeleaf项目的构建中,需要进行如下步骤: 1. 首先,引入Spring BootThymeleaf依赖以及其他必要的依赖,例如web和mybatis等相关组件。 2. 创建一个Controller类,并使用@Controller注解将类标记为Controller,编写具体的Action方法,这些方法可以用@RequestMapping或@GetMapping等注解来定义处理请求的URL路径和请求类型等相关信息。 3. 创建一个Model类,用于封装需要传输到前端的数据和相关操作等。 4. 在Controller内部设置Model变量并将相关数据注入Model,然后将需要展现的数据作为参数传递给Thymeleaf进行渲染,最后将渲染完成后的结果返回给前端页面展现。 5. 编写HTML页面,使用Thymeleaf标签来渲染动态数据。 需要注意的是,在进行Thymeleaf模板的渲染时,需要遵守一定的规范,例如页面中的数据变量名称需与Model中的属性名称一致,引入Thymeleaf命名空间等等。 总之,Spring BootThymeleaf结合使用可以帮助开发人员快速地完成Web开发,整个过程简单而且高效。使用Thymeleaf能够降低模版制作的门槛,进一步提高开发效率,并且能够提供丰富的模版处理标签,使得页面制作更加灵活。 ### 回答3: 近年来,使用SpringBootThymeleaf进行Web开发已经成为越来越多的开发者选择的方案。SpringBoot是一个基于Spring框架的快速Web应用开发框架,而Thymeleaf是一种基于HTML的模板引擎,其中需要了解的内容包括以下几点: 首先,SpringBoot框架的优点是非常明显的。它提供了很多便于使用的方法,例如自动装配,以及基于配置的许多默认值。这使得开发者可以花更少的时间和精力来开发项目,将重点放在业务逻辑和功能实现上。 其次,Thymeleaf是一种非常强大和灵活的模板引擎,其语法简单易懂,而且支持HTML5标准。它还提供了一些样式和布局的工具,以及易于使用的表达式和标签,使得Web页面开发更加容易。 当然,SpringBoot集成Thymeleaf的过程也并不复杂。只需添加thymeleaf-starter包依赖SpringBoot将自动将Thymeleaf注册为默认的模板引擎。然后,您只需要编写Thymeleaf模板文件即可。 最后,值得注意的是,使用SpringBootThymeleaf进行Web开发的好处在于它们之间的紧密集成。这种紧密集成可以更轻松地创建动态和交互性的Web应用程序,这是传统的HTML和JavaScript不能提供的。 总的来说,SpringBootThymeleaf是一对非常强大且易于使用的Web开发工具组合,它们的出现大大提高了Web开发的效率和质量,同时也为开发人员提供了更好的开发体验。我们相信,这对于Web开发者来说是非常有价值的组合。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值