• 11_Spring Boot 集成Thymeleaf模板


    一、认识Thymeleaf

    Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发

    模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎,甚至在JavaScript中也会用到模板引擎技术,Java生态下的模板引擎有 Thymeleaf 、Freemaker、Velocity、Beetl(国产) 等

    Thymeleaf 对网络环境不存在严格的要求,既能用于Web环境下,也能用于非Web环境下。在非Web环境下,他能直接显示模板上的静态数据在Web环境下,它能像Jsp一样从后台接收数据并替换掉模板上的静态数据它是基于HTML的,以HTML标签为载体,Thymeleaf要寄托在HTML标签下实现

    Spring Boot 集成了Thymeleaf模板技术,并且Spring Boot官方也推荐使用Thymeleaf来替代JSP技术,Thymeleaf是另外的一种模板技术,它本身并不属于Spring Boot,Spring Boot只是很好地集成这种模板技术,作为前端页面的数据展示,在过去的Java Web开发中,我们往往会选择使用Jsp去完成页面的动态渲染,但是jsp需要翻译编译运行,效率低

    Thymeleaf的官方网站:

    Thymeleafhttp://www.thymeleaf.org

    Thymeleaf官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.htmlhttps://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

    二、Spring Boot集成Thymeleaf

    1.创建Spring Boot项目,添加web和Thymeleaf依赖

    (1)添加web依赖 

    (2)添加Thymeleaf依赖  

    (3)按照这种方式创建后,pom.xml文件下会自动添加如下依赖 

    2. 在Spring boot的核心配置文件application.properties中对Thymeleaf进行配置

    1. server.port=9012
    2. server.servlet.context-path=/012-springboot-thymeleaf

    3. 创建ThymeleafControlle去映射到模板页面(和SpringMVC基本一致)

    在com.suke.springboot.web包下创建ThymeleafController类

    1. @Controller
    2. public class ThymeleafController {
    3. /*
    4. * http://localhost:9012/012-springboot-thymeleaf/springboot/thymeleaf/index
    5. * */
    6. @RequestMapping(value = "/springboot/thymeleaf/index")
    7. public String index(HttpServletRequest request, Model model) {
    8. model.addAttribute("data", "恭喜您,SpringBoot集成Thymeleaf成功");
    9. return "index";
    10. }
    11. }

    4. 在src/main/resources的templates下新建一个index.html页面用于展示数据

    注意:Springboot使用thymeleaf作为视图展示,约定将模板文件放置在src/main/resource/templates目录下,静态资源放置在src/main/resource/static目录下

    HTML页面的<html>元素中加入以下属性:

    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>SpringBoot集成Thymeleaf</title>
    6. </head>
    7. <body>
    8. <!--Thymeleaf前端框架以Html为载体-->
    9. <span th:text="${data}"></span>
    10. <span th:text="${data}"></span>
    11. <p th:text="${data}"></p>
    12. <div th:text="${data}"></div>
    13. </body>
    14. </html>

    问题:data 爆红

    解决办法一:通过Alt+Enter进行自动生成的注释,补全IDEA;如果不加,IDEA将会报错cannot reslove

    解决办法二:通过Alt+Enter选择Edit inspection profile setting修改

    可以将error改成Warning,或者将√取消掉

    5. 启动程序,浏览器访问

    (1)页面展示

    (2)右键->查看页面源代码

    三、Thymeleaf的表达式

    1. 标准变量表达式

    注意:th:text="" 是Thymeleaf的一个属性,用于文本的显示

     语法: ${...}


    标准变量表达式用于访问容器(tomcat)上下文环境中的变量,功能和EL中的 ${} 相同。Thymeleaf 中的变量表达式使用 ${变量名} 的方式获取Controller中model其中的数据${age} 

    (1)创建实体User

    com.suke.springboot.model包下创建User实体类

    1. public class User implements Serializable {
    2. private Integer id;
    3. private String nick;
    4. private String phone;
    5. private String address;
    6. public User() {
    7. }
    8. public User(Integer id, String nick, String phone, String address) {
    9. this.id = id;
    10. this.nick = nick;
    11. this.phone = phone;
    12. this.address = address;
    13. }
    14. public Integer getId() {
    15. return id;
    16. }
    17. public void setId(Integer id) {
    18. this.id = id;
    19. }
    20. public String getNick() {
    21. return nick;
    22. }
    23. public void setNick(String nick) {
    24. this.nick = nick;
    25. }
    26. public String getPhone() {
    27. return phone;
    28. }
    29. public void setPhone(String phone) {
    30. this.phone = phone;
    31. }
    32. public String getAddress() {
    33. return address;
    34. }
    35. public void setAddress(String address) {
    36. this.address = address;
    37. }
    38. }

    (2)创建ThymeleafController类

    ThymeleafController中添加user方法中,向model放入User对象

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/user
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/user")
    5. public String user(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. return "user";
    9. }

    (3) 在src/main/resources/templates在创建user.html页面

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Thymeleaf标准变量表达式</title>
    6. </head>
    7. <body>
    8. <h2>Thymeleaf以HTML为载体展示数据</h2>
    9. <h2>展示用户信息:</h2>
    10. <span th:text="${user}"></span><br>
    11. <span th:text="${user.id}"></span><br>
    12. <span th:text="${user.nick}"></span><br>
    13. <span th:text="${user.getPhone()}"></span><br>
    14. <span th:text="${user.getAddress()}"></span><br>
    15. </body>
    16. </html>

    (4)启动程序,浏览器访问 

    2. 选择变量表达式(了解,不推荐使用

    语法:*{...}


    • 选择变量表达式,也叫星号变量表达式,使用 th:object 属性来绑定对象
    • 选择表达式首先使用th:object来绑定后台传来的User对象,然后使用 * 来代表这个对象,后面 {} 中的值是此对象中的属性。
    • 选择变量表达式 *{...} 是另一种类似于标准变量表达式 ${...} 表示变量的方法
    • 选择变量表达式在执行时是在选择的对象上求解,而${...}是在上下文的变量Model上求解,这种写法比标准变量表达式繁琐,只需要大家了解即可

    (1)user.html页面

    1. <h2>选择变量表达:又叫做*号表达式</h2>
    2. <h3 style="color: red">用户对象仅在div范围内有效</h3>
    3. <div th:object="${user}">
    4. <span th:text="*{id}"></span><br/>
    5. <span th:text="*{nick}"></span><br/>
    6. <span th:text="*{phone}"></span><br/>
    7. <span th:text="*{address}"></span><br/>
    8. </div>

    (2)启动程序,浏览器访问 

    3. 标准变量表达式和选择变量表达式

    标准变量表达式和选择变量表达式可以混合一起使用, 也可以不使用 th:object 进行对象的选择,而直接使用 *{...} 获取数据

    (1)user.html页面

    1. <h3 style="color: red">2.选择变量表达式其它用法展示数据</h3>
    2. <div>
    3. <span th:text="*{user.id}"></span><br/>
    4. <span th:text="*{user.nick}"></span><br/>
    5. <span th:text="*{user.phone}"></span><br/>
    6. <span th:text="*{user.address}"></span><br/>
    7. </div>

    (2)启动程序,浏览器访问 

    4. URL表达式

    语法:@{...}


    主要用于链接、地址的展示,可用于<script src="...">、<link href="...">、<a href="...">、<form action="...">、<img src="">等,可以在URL路径中动态获取数据

    (1)ThymeleafController类中添加url方法

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/url
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/url")
    5. public String url(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. return "url";
    9. }

    (2)在url.html页面中加入如下代码

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>URL表达式</title>
    6. </head>
    7. <body>
    8. <!--
    9. 绝对路径:协议开头 盘符 /
    10. -->
    11. <a href="http://www.baidu.com">baidu</a>
    12. <a href="D:\IT\Java\IdeaProjects\Suke2\06-SpringBoot\012-springboot-thymeleaf\src\main\resources\templates">index1</a>
    13. <a href="/012-springboot-thymeleaf/springboot/thymeleaf/index">index2</a>
    14. <hr>
    15. <a th:href="@{/012-springboot-thymeleaf/thymeleaf/expression/user}">user1</a>
    16. <a th:href="@{/thymeleaf/expression/user}">user2</a>
    17. <a th:href="@{/thymeleaf/expression/user?name=zsf&age=120}">user3</a>
    18. <a th:href="@{'/thymeleaf/expression/user?name='+${user.nick}+'&age=120'}">user4</a>
    19. <a th:href="@{/thymeleaf/expression/user(name=${user.nick},age=110)}">user5</a>
    20. <hr>
    21. <!--
    22. 相对路径:相对当前资源所在目录 计算出来的路径
    23. ① http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/url
    24. ② http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/
    25. ③ http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/user
    26. ① http://localhost:9012/012-springboot-thymeleaf/springboot/thymeleaf/index
    27. ② ../../springboot/thymeleaf/index
    28. -->
    29. <a href="user">user6</a>
    30. <a href="./user">user7</a>
    31. <a href="../../springboot/thymeleaf/index">index3</a>
    32. <a th:href="@{./user}">user8</a>
    33. <a th:href="@{./user(name=${user.nick},age=130)}">user9</a>
    34. </body>
    35. </html>

    (3)启动程序,浏览器访问 

    (4)右键查看源代码

    四、Thymeleaf 的常见属性

    1. th:action

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

    (1)在ThymeleafController类中添加action方法

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/action
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/action")
    5. public String action(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. return "action";
    9. }

    (2) 在action.html页面中加入如下代码

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>action的使用</title>
    6. </head>
    7. <body>
    8. <h1>th:action的使用</h1>
    9. <div>当你需要动态获取变量数据的时候,就需要加th前缀</div>
    10. <form id="login" th:action="@{'/login/' + ${user.id}}"></form>
    11. <div>以下两种方式获取不到用户的id</div>
    12. <form id="login2" action="/login/${user.id}"></form>
    13. <form id="login3" action="/login"+${user.id}></form>
    14. </body>
    15. </html>

    (3)启动程序,浏览器访问 

    思考:为什么login3中${user.id} 获取不到数据?

    因为我们Thymeleaf是以html为载体的,所以html不会认识${}语法。

    我们请求的流程是,发送请求给服务器,服务器接收请求后,处理请求,跳转到指定的静态html页面,在服务器端,Thymeleaf模板引擎会按照它的语法,对动态数据进行处理,所以如果要是th开头,模板引擎能够识别,会在服务器端进行处理,获取数据;如果没有以th开头,那么Thymeleaf模板引擎不会处理,直接返回给客户端了。

    在页面渲染之前,Thymeleaf模板引擎会作用(获得后台数据),把th开头的标签静态内容,换成动态数据,如果要是th开头,模板引擎不处理。

    2. th:method

    设置请求方法

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

    3. th:href

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

    4. th:src

    用于外部资源引入,比如<script>标签的src属性,<img>标签的src属性,常与@{}表达式结合使用,在SpringBoot项目的静态资源都放到resources的static目录下

    放到static路径下的内容,写路径时不需要写上static

    (1)在ThymeleafController类中添加src方法

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/src
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/src")
    5. public String src(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. return "src";
    9. }

    (2) 在src.html页面中加入如下代码

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>src使用</title>
    6. </head>
    7. <body>
    8. <h1>th:src使用</h1>
    9. <script src="/static/js/jquery-1.7.2.min.js"></script>
    10. <script th:src="@{/js/jquery-1.7.2.min.js}"></script>
    11. <img th:src="@{/img/ls.jpg}">
    12. </body>
    13. </html>

    (3)启动程序,浏览器访问 

    这种方式比传统方式的好处是,在URL表达式前加/,会自动加上上下文根,避免404找不到资源的情况。

    5. th:id

    类似html标签中的id属性

    <span th:id="${hello}">aaa</span>

    6. th:name

    设置名称

    <input th:type="text" th:id="userName" th:name="userName">

    7. th:value

    类似html标签中的value属性,能对某元素的value属性进行赋值

    <input type="hidden" id="userId" name="userId" th:value="${userId}">

    ​​​​​​8. th:attr

    该属性也是用于给HTML中某元素的某属性赋值,但该方式写法不够优雅

    比如上面的例子可以写成如下形式

    <input type="hidden" id="userId" name="userId" th:attr="value=${userId}" >

    好处是可以给html中没有定义的属性动态的赋值

    (1) 在html页面中加入如下代码

    1. <input type="text" id="userId" name="userId" th:value="${user.id}">
    2. <!--thymeleaf没有对应的th标签,所以${user.id}不能被识别-->
    3. <span zhangsan=${user.id}></span>
    4. <!--通过th:attr对自定义的属性赋值-->
    5. <span id="zs" th:attr="zhangsan=${user.id}"></span>
    6. <script>
    7. $(function () {
    8. alert("=====" + $("#zs").attr("zhangsan"));
    9. alert("=====" + document.getElementById("zs").zhangsan);
    10. });
    11. </script>

    (2)启动程序,浏览器访问 

     

    9. th:text

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

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

    10. th:object

    用于数据对象绑定

    通常用于选择变量表达式(星号表达式)

    11. th:onclick

    点击事件:th:οnclick="'getCollect()'"

    js不能跨域(站点)访问   jsonp:跨域访问(利用script src标签的漏洞)

    (1) 在html页面中加入如下代码 

    1. <!--目前thymeleaf版本要求只能传递数字和布尔类型-->
    2. <a th:onclick="'fun1('+${user.id}+')'">点击我</a>
    3. <script type="text/javascript">
    4. function fun1(userId) {
    5. alert(userId);
    6. }
    7. </script>

    (3)启动程序,浏览器访问

     

    12. th:style

    设置样式

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

    13. th:each

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

    (1)创建each.htmleach(Array、List、Set、Map)集合进行遍历 

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>each遍历的使用</title>
    6. </head>
    7. <body>
    8. <h1>th:each遍历Array数据集合</h1>
    9. <div th:each="array,arrayState:${userArray}">
    10. <span th:text="${arrayState.first}"></span>--
    11. <span th:text="${arrayState.last}"></span>--
    12. <span th:text="${arrayState.even}"></span>--
    13. <span th:text="${arrayState.odd}"></span>--
    14. <span th:text="${arrayState.index}"></span>--
    15. <span th:text="${arrayState.count}"></span>--
    16. <span th:text="${arrayState.current}"></span>-->
    17. <span th:text="${array.id}"></span>
    18. <span th:text="${array.phone}"></span>
    19. <span th:text="${array.nick}"></span>
    20. <span th:text="${array.address}"></span>
    21. </div>
    22. <h1>th:each遍历List集合 for each</h1>
    23. <div th:each="list,listState:${userList}">
    24. <span th:text="${listState.first}"></span>--
    25. <span th:text="${listState.last}"></span>--
    26. <span th:text="${listState.even}"></span>--
    27. <span th:text="${listState.odd}"></span>--
    28. <span th:text="${listState.index}"></span>--
    29. <span th:text="${listState.count}"></span>--
    30. <span th:text="${listState.current}"></span>-->
    31. <span th:text="${list.getId()}"></span>
    32. <span th:text="${list.getPhone()}"></span>
    33. <span th:text="${list.getNick()}"></span>
    34. <span th:text="${list.address}"></span>
    35. </div>
    36. <h1>th:each遍历Set集合 for each</h1>
    37. <div th:each="set,setState:${userSet}">
    38. <span th:text="${setState.index}"></span>--
    39. <span th:text="${setState.last}"></span>--
    40. <span th:text="${setState.even}"></span>--
    41. <span th:text="${setState.odd}"></span>--
    42. <span th:text="${setState.index}"></span>--
    43. <span th:text="${setState.count}"></span>--
    44. <span th:text="${setState.current}"></span>-->
    45. <span th:text="${set.getId()}"></span>
    46. <span th:text="${set.getPhone()}"></span>
    47. <span th:text="${set.getNick()}"></span>
    48. <span th:text="${set.address}"></span>
    49. </div>
    50. <h1>th:each遍历map集合 entrySet Map.Entry for each </h1>
    51. <h1>1+1=2, 2 </h1>
    52. <div th:each="map,mapState:${userMap}">
    53. <span th:text="${mapState.index}"></span>--
    54. <span th:text="${map.key}"></span>--
    55. <span th:text="${map.value}"></span>-->
    56. <span th:text="${map.value.getId()}"></span>
    57. <span th:text="${map.value.getPhone()}"></span>
    58. <span th:text="${map.value.getNick()}"></span>
    59. <span th:text="${map.value.address}"></span>
    60. </div>
    61. <h1>遍历复杂的集合:List -> Map -> List -> User</h1>
    62. <!--首先遍历List,获取Map-->
    63. <span th:each="myMap,listStat:${myList}">
    64. <!--再次遍历Map,获取List-->
    65. <span th:each="myKeyValue:${myMap}">
    66. <!--获取当前Map集合的Id-->
    67. <span th:text="${myKeyValue.key}"></span>--
    68. <span th:each="user,listSate:${myKeyValue.value}">-->
    69. <span th:text="${user.id}"></span>
    70. <span th:text="${user.phone}"></span>
    71. <span th:text="${user.nick}"></span>
    72. <span th:text="${user.address}"></span>
    73. <br/>
    74. </span>
    75. </span>
    76. </span>
    77. </body>
    78. </html>

    ​​​​​​A. ​遍历Array数组

    (2)在ThymeleafController中添加eachArray方法,准备集合数据

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/array
    3. * */
    4. @RequestMapping(value = "thymeleaf/each/array")
    5. public String eachArray(Model model) {
    6. User[] userArray = new User[10];
    7. for (int i = 0; i < 10; i++) {
    8. User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
    9. userArray[i] = user;
    10. }
    11. model.addAttribute("userArray", userArray);
    12. return "each";
    13. }

    B. 遍历List集合​​​​​​​

    (2)在ThymeleafController中添加eachList方法,准备集合数据

    代码说明

    ① th:each="user, iterStat : ${userlist}"中的 ${userList} :是后台传过来的集合

    ② user:定义变量,去接收遍历${userList}集合中的一个数据

    ③ iterStat :${userList} 循环体的信息

    ④ 其中user及iterStat自己可以随便取名

    ⑤ interStat是循环体的信息,通过该变量可以获取如下信息

            index: 当前迭代对象的index(从0开始计算)

            count: 当前迭代对象的个数(从1开始计算)这两个用的较多

            size: 被迭代对象的大小

            current: 当前迭代变量

            even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算)

            first: 布尔值,当前循环是否是第一个

            last: 布尔值,当前循环是否是最后一个

    注意:循环体信息interStat也可以不定义,则默认采用迭代变量加上Stat后缀,即userStat

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/list
    3. * */
    4. @RequestMapping("/thymeleaf/each/list")
    5. public String eachList(Model model) {
    6. List<User> userList = new ArrayList<User>();
    7. for (int i = 0; i < 10; i++) {
    8. User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
    9. userList.add(user);
    10. }
    11. model.addAttribute("userList", userList);
    12. return "each";
    13. }

    C. 遍历Set集合

    (2)在ThymeleafController中添加eachSet方法,准备集合数据

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/set
    3. * */
    4. @RequestMapping("/thymeleaf/each/set")
    5. public String eachSet(Model model) {
    6. Set userSet = new HashSet();
    7. for (int i = 0; i < 10; i++) {
    8. User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
    9. userSet.add(user);
    10. }
    11. model.addAttribute("userSet", userSet);
    12. return "each";
    13. }

    D. 遍历Map集合

    (2)在ThymeleafController中添加eachMap方法,准备集合数据

    代码说明

    ① th:each="map:${userMap}" : 用map接收每次遍历的结果,封装为一个键值对

    ② map.key : 获取当前键值对中的key

    ③ map.value : 获取当前键值对中的value

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/map
    3. * */
    4. @RequestMapping(value = "/thymeleaf/each/map")
    5. public String eachMap(Model model) {
    6. Map<Integer, Object> userMap = new HashMap<Integer, Object>();
    7. for (int i = 0; i < 10; i++) {
    8. User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
    9. userMap.put(i, user);
    10. }
    11. model.addAttribute("userMap", userMap);
    12. return "each";
    13. }

    ​​​​​​​D. 比较复杂的循环案例

    (2)在ThymeleafController中添加eachAll方法,准备集合数据

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/each/all
    3. * */
    4. @RequestMapping(value = "/thymeleaf/each/all")
    5. public String eachAll(Model model) {
    6. //构造复杂的数据关系 List->Map->List->User
    7. List<Map<Integer, List<User>>> userAll = new ArrayList<Map<Integer, List<User>>>();
    8. for (int n = 0; n < 2; n++) {
    9. Map<Integer, List<User>> myMap = new HashMap<Integer, List<User>>();
    10. for (int m = 0; m < 2; m++) {
    11. List<User> myList = new ArrayList<User>();
    12. for (int i = 0; i < 3; i++) {
    13. User user = new User(100 + i, "何幸福" + i, "2120010722" + i, "苏州科技大学" + i);
    14. myList.add(user);
    15. }
    16. myMap.put(m, myList);
    17. }
    18. userAll.add(myMap);
    19. }
    20. model.addAttribute("userAll", userAll);
    21. return "each";
    22. }

    14.条件判断

    (1)创建condition.html页面进行条件判断

    A. ​​​​​​​th:if

    B. th:unless(了解)

    C. th:switch/th:case

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>条件判断</title>
    6. </head>
    7. <body>
    8. <div style="color: red">th:if条件判断:如果满足条件,显示标签,如果不满足条件,标签就不显示</div>
    9. <!--th:if条件判断:如果满足条件,显示标签,如果不满足条件,标签就不显示-->
    10. <span th:if="${sex == 1}">
    11. 男:<input type="radio" name="sex" th:value="男"/>
    12. </span>
    13. <span th:if="${sex==2}">
    14. 女:<input type="radio" name="sex" th:value="女"/>
    15. </span>
    16. <hr>
    17. <span th:if="${sex == '1'}">
    18. 男:<input type="radio" name="sex" th:value="男"/>
    19. </span>
    20. <span th:unless="${sex==1}">
    21. 女:<input type="radio" name="sex" th:value="女"/>
    22. </span>
    23. <hr>
    24. <div th:switch="${sex}">
    25. <p th:case="1">性别:男</p>
    26. <p th:case="2">性别:女</p>
    27. <p th:case="*">性别:未知</p>
    28. </div>
    29. </body>
    30. </html>

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

    (2)在ThymeleafController中添加condition方法,通过model传递sex值为1

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/condition
    3. * */
    4. @RequestMapping(value = "/thymeleaf/condition")
    5. public String condition(Model model) {
    6. //model.addAttribute("sex",1);
    7. model.addAttribute("sex", "1");
    8. return "condition";
    9. }

    ​​​​​​​15. th:inline

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

    (1)ThymeleafController中添加inline方法

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/inline
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/inline")
    5. public String inline(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. return "inline";
    9. }

    ​​​​​​​A. 内敛文本(th:inline=”text”)

    可以让Thymeleaf表达式不依赖于html标签,直接使用内敛表达式[[表达式]]即可获取动态数据,要求在父级标签上加th:inline = “text”属性

    (2)在inline.html页面上,加如下代码

    1. <!--内敛文本-->
    2. 标准变量表达式用户数据的展示:<br>
    3. <span th:text="${user.id}"></span>
    4. <span th:text="${user.nick}"></span>
    5. <span th:text="${user.phone}"></span>
    6. <span th:text="${user.address}"></span>
    7. <br>
    8. <!--以上代码可以使用内敛文本代替-->
    9. 内敛表达式 用户数据的展示:<br>
    10. <span th:inline="text">
    11. [[${user.id}]]
    12. [[${user.nick}]]
    13. [[${user.phone}]]
    14. [[${user.address}]]
    15. </span>
    16. <br>

     注意:一般我们将<span th:inline="text">放到<body th:inline="text">标签中

    B. 内敛脚本(th:inline=”javascript”)

    js代码中获取后台的动态数据

    (2)在inline.html页面上,加如下代码

    1. <button type ="button" onclick="func()">抽奖</button>
    2. <script type="text/javascript" th:inline="javascript">
    3. function func(){
    4. alert("恭喜" + [[${user.nick}]] +"手机号为"+[[${user.phone}]]+"中奖!");
    5. }
    6. </script>

    (3)启动程序,浏览器访问

    五、hymeleaf字面量(直接量

    int a=100;    fun(a)    fun(100)

    变量:a  

    直接量:100

    字面量:对应数据类型的合法取值,可以在html页面直接使用,不需要后台传递

    (1)ThymeleafController中添加literal方法

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/literal
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/literal")
    5. public String literal(Model model) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. model.addAttribute("sex", 1);
    9. model.addAttribute("cunPage", 8);
    10. model.addAttribute("totalPage", 41);
    11. return "literal";
    12. }

    1. 文本字面量

    用单引号'...'包围的字符串为文本字面量

    1. <!--文本字面量-->
    2. <a th:href="@{'/user/' + ${user.id}}">修改用户</a>

    ​​​​​​2. ​数字字面量

    1. <!--数字字面量-->
    2. <p>今年是<span th:text="2017">1949</span></p>
    3. <p>20年后, 将是<span th:text="2017 + 20">1969</span></p>

    ​​​​​​3. boolean字面量

    true false

    1. <!--boolean字面量-->
    2. <p th:if="${sex == true}">执行操作</p>

    ​​​​​​​4. null字面量​​​​​​​

    1. <!--null字面量-->
    2. <p th:if="${user == null}">user为空</p>
    3. <p th:if="${user != null}">user不为空</p>

    (2)在literal.html页面上,加如下代码

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>字面量的使用</title>
    6. </head>
    7. <body>
    8. <!--文本字面量-->
    9. <a th:href="@{'/user/' + ${user.id}}">修改用户</a>
    10. <!--数字字面量-->
    11. <p>今年是<span th:text="2017">1949</span></p>
    12. <p>20年后, 将是<span th:text="2017 + 20">1969</span></p>
    13. <!--boolean字面量-->
    14. <p th:if="${sex == true}">执行if操作</p>
    15. <p th:unless="${sex == true}">执行unless操作</p>
    16. <!--null字面量-->
    17. <p th:if="${user == null}">user为空</p>
    18. <p th:if="${user != null}">user不为空</p>
    19. <span th:text="${sex==1?'boy':'girl'}"></span>
    20. <span th:text="${sex eq 1?'boy':'girl'}"></span>
    21. <hr>
    22. <!--一种是字面量使用加号拼接-->
    23. <span th:text="'当前是第'+${cunPage}+'页,共'+${totalPage}+'页'"></span>
    24. <br>
    25. <span th:text="|当前是第${cunPage}页,共${totalPage}页|"></span>
    26. </body>
    27. </html>

    六、Thymeleaf 字符串拼接

    1. <!--一种是字面量使用加号拼接-->
    2. <span th:text="'当前是第'+${sex}+'页 ,共'+${sex}+'页'"></span>
    3. <!--另一种更优雅的方式,使用“|”减少了字符串的拼接的加号-->
    4. <span th:text="|当前是第${sex}页,共${sex}页|"></span>

    ​​​​​​​七、Thymeleaf运算符

    三元运算: sex == 1? '男' : '女'

    算术运算:+ , - , * , / , %

    关系比较: > , < , >= , <= ( gt , lt , ge , le )

    相等判断:== , != ( eq , ne )

    1. <span th:text="${sex == 1?'男':'女'}"></span>
    2. <span th:text="${sex eq 1?'男':'女'}"></span>

    ​​​​​​​八、Thymaleaf表达式基本对象

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

    1. ​​​​​​​#request

    相当于httpServletRequest 对象,这是3.x版本,若是2.x版本使用 #httpServletRequest

    ​​​​​​2. ​#session

    相当于HttpSession 对象,这是3.x版本,若是2.x版本使用#httpSession

    (1)ThymeleafController中添加inlineObj方法 

    1. /*
    2. * http://localhost:9012/012-springboot-thymeleaf/thymeleaf/expression/inlineObj
    3. * */
    4. @RequestMapping(value = "/thymeleaf/expression/inlineObj")
    5. public String inlineObj(Model model, HttpServletRequest request) {
    6. User user = new User(100, "何幸福", "21200107226", "苏州科技大学");
    7. model.addAttribute("user", user);
    8. model.addAttribute("sex", 1);
    9. request.setAttribute("birthday", new Date());
    10. request.getSession().setAttribute("salary", 12500);
    11. return "inlineObj";
    12. }

    (2)在inlineObj.html页面上,加如下代码

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>表达式基本对象的使用</title>
    6. </head>
    7. <body th:inline="text">
    8. <span th:text="${#request.getAttribute('birthday')}"></span>
    9. <span th:text="${#session.getAttribute('salary')}"></span>
    10. <hr>
    11. [[${#request.getAttribute('birthday')}]]--[[${#session.getAttribute('salary')}]]<br>
    12. [[${#request.getRequestURI()}]]--[[${#request.getContextPath()}]]
    13. <hr>
    14. <span th:text="${#strings.substring(user.getPhone(),1,8)}"></span>
    15. <span th:text="${#dates.format(#request.getAttribute('birthday'),'yyyy-MM-dd HH:mm:ss')}"></span>
    16. <br>
    17. <span th:text="${#numbers.formatDecimal(#session.getAttribute('salary'),10,10)}"></span>
    18. <br>
    19. <span th:text="${#numbers.formatDecimal(#session.getAttribute('salary'),2,3)}"></span>
    20. </body>
    21. </html>

    ​​​​​​​九、Thymaleaf表达式功能对象(了解)

    模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的功能方法

    工作中常使用的数据类型,如集合,时间,数值,可以使用Thymeleaf的提供的功能性对象来处理它们。

    内置功能对象前都需要加#号,内置对象一般都以s结尾

    官方手册:​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​Tutorial: Using Thymeleafhttp://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

    #dates: java.util.Date对象的实用方法,<span th:text="${#dates.format(curDate, 'yyyy-MM-dd HH:mm:ss')}"></span>

    #calendars: 和dates类似, 但是 java.util.Calendar 对象;

    #numbers: 格式化数字对象的实用方法;

    #strings: 字符串对象的实用方法: contains, startsWith, prepending/appending等;

    #objects: 对objects操作的实用方法;

    #bools: 对布尔值求值的实用方法;

    #arrays: 数组的实用方法;

    #lists: list的实用方法,比如<span th:text="${#lists.size(datas)}"></span>

    #sets: set的实用方法;

    #maps: map的实用方法;

    #aggregates: 对数组或集合创建聚合的实用方法;

  • 相关阅读:
    石家庄正定县恢复种植 国稻种芯·中国水稻节:河北绘就画卷
    HashMap源码解析
    HarmonyOS ArkUI滚动类组件-Scroll、Scroller
    Linux—-vim基础使用
    css 星星闪烁加载框
    深度学习的进展
    操作系统学习
    C++学习day6
    总结 NAT 机制的工作流程及优缺点
    SQL Server多实例之间触发器同步数据
  • 原文地址:https://blog.csdn.net/qq_45037155/article/details/125547433