7、SpringBoot整合Thymeleaf

步骤

  1. 创建项目
  2. 修改POM文件,添加Thymeleaf启动器依赖
  3. 创建Controller
  4. 创建视图

添加依赖

<!--添加Thymeleaf启动器依赖-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

注意:template是安全级别比较高的一个目录,不可以直接访问目录下的资源,而static目录下的资源就可以直接访问;

创建Controller

/**
* 页面跳转controller
*/
@Controller
public class PageController {
    @GetMapping("/show")
    public String showPage(Model model){
        model.addAttribute("msg", "Merry Christmas Mr lawrence");
        return "index";
    }
}

创建视图

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
</head>
<body>
    <h1>Rain</h1>
    <span th:text="圣诞快乐,劳伦斯先生"></span>
    <hr/>
    <span th:text="${msg}"></span>
</body>
</html>

Thymeleaf命名空间

加入该语句于html标签中,则该页面在写thymeleaf表达式的时候会有提示

xmlns:th="http://www.thymeleaf.org"

Thymeleaf语法

th:text

用于字符串或变量的输出,例如
<span th:text="the last emperor"></span>
或
<span th:text="${msg}"></span>

内置对象

Thymeleaf提供了一些内置对象,内置对象可直接在模板中使用,这些对象是以#引用的。
Thymeleaf内容对象的主要作用是针对于一些类型的数据去处理的一些对象

内置对象的语法

1、引用内置对象需要使用#
2、大部分内置对象的名称都以s结尾,如:strings、number、dates

判断字符串是否为空,如果为空返回true,否则返回false

${#strings.isEmpty(key)}

判断字符串是否包含指定的子串,如果包含返回true,否则返回false

${#strings.contains(msg,"T")} 

判断当前字符串是否以子串开头,如果是返回true,否则返回false

${#strings.startWith(msg,'a')} 

判断当前字符串是否以子串结尾,如果是返回true,否则返回false

${#strings.endWith(msg,'a')}

返回字符串的长度

${#strings.length(msg)}

查找子串的位置,并返回该子串的下标,如果没找到则返回-1

${#strings.indexOf(msg,'h')}

截取子串,用户与jdk String类下SubString方法相同

${#strings.substring(msg,2)}
${#strings.substring(msg,2,5)}

字符串转大小写

${#strings.toUpperCase(msg)}
${#strings.toLowerCase(msg)}

日期格式化处理

格式化日期,默认的以浏览器默认语言为格式化标准

${#dates.format(key)}

按照自定义的格式做日期转换

${#dates.format(key,'yyyy/MM/dd')}

分别取日期中“年”,“月”,“日”

${#dates.year(key)}
${#dates.month(key)}
${#dates.day(key)}

条件判断

if条件判断

th:if

th:switch/th:case

th:switch/th:case 与 Java中的switch语句等效;
有条件地显示匹配的内容,如果有多个匹配结果只选择第一个显示;
th:case=“*”表示Java中switch的default,即没有case的值为true时则显示 th:case=“*”的内容。

迭代遍历

迭代器,用于循环迭代集合

th:each

状态变量
index:当前迭代器的索引,从0开始
count:当前迭代对象的计数,从1开始
size:被迭代对象的长度
odd/even:布尔值,当前循环是否是偶数/奇数 从0开始
first:布尔值,当前循环的是否是第一条,如果是返回true,否则返回false
last:布尔值,当前循环的是否是最后一条,如果是则返回true,否则返回false

th:each 迭代List

pojo

package com.example.springbootthmeleaf.pojo;


public class Users {

    private String id;
    private String name;
    private int age;

    //有参,无参构造方法省略,get,set方法省略
}

controller

@GetMapping("/show")
public String showPage(Model model){
   
    List<Users> list = new ArrayList<>();
    list.add(new Users("1","admin",23));
    list.add(new Users("2","kevin",23));
    list.add(new Users("3","lin",23));
    model.addAttribute("list",list);
    return "index";
}

html

<table border="1" width="50%">
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Age</th>
        <th>Index</th>
        <th>Count</th>
        <th>Size</th>
        <th>Odd</th>
        <th>Even</th>
        <th>First</th>
        <th>Last</th>
    </tr>
    <tr th:each="u, ztbl : ${list}">
        <td th:text="${u.id}"></td>
        <td th:text="${u.name}"></td>
        <td th:text="${u.age}"></td>
        <td th:text="${ztbl.index}"></td>
        <td th:text="${ztbl.count}"></td>
        <td th:text="${ztbl.size}"></td>
        <td th:text="${ztbl.odd}"></td>
        <td th:text="${ztbl.even}"></td>
        <td th:text="${ztbl.first}"></td>
        <td th:text="${ztbl.last}"></td>
    </tr>
</table>

结果如下

th:each 迭代Map

迭代Set和迭代list的方式是相同的
迭代Map则与Set和List有区别,毕竟数据结构不一样

controller

@GetMapping("/show")
public String showPage(Model model){
    Map<String, Users> map = new HashMap<>();
    map.put("user1",new Users("1","admin",23));
    map.put("user2",new Users("2","kevin",24));
    map.put("user3",new Users("3","lin",25));
    model.addAttribute("map",map);

    return "index";
}

html

<table border="1" width="50%">
    <tr>
        <th>Value</th>
    </tr>
    <tr th:each="m : ${map}">
        <td th:text="${m}"></td>
    </tr>
</table>
<hr />
<table border="1" width="50%">
    <tr>
        <th>key</th>
        <th>id</th>
        <th>name</th>
        <th>age</th>
    </tr>
    <tr th:each="m : ${map}">
        <td th:text="${m.key}"></td>
        <td th:text="${m.value.id}"></td>
        <td th:text="${m.value.name}"></td>
        <td th:text="${m.value.age}"></td>
    </tr>
</table>

效果如下:

操作域对象

HttpServletRequest

request.setAttribute("req","HttpServletRequest");
<span th:text="${#httpServletRequest.getAttribute('req')}"></span>
<span th:text="${#request.getAttribute('req')}"></span>

HttpSession

request.getSession().setAttribute("sess","HttpSession");
<span th:text="${seesion.sess}"></span><br/>
<span th:text="${#session.getAttribute("sess")}"><span><br/>

ServletContext

request.getSession().getServletContext().setAttribute("app","Application")
<span th:text="${application.app}"></span>
<span th:text="${#SservletContext.getAttribute('app')}">

URL表达式

语法:thymeleaf中URL表达式的语法格式为@{}

绝对路径

<a th:href="@{http://www.baidu.com}">绝对路径</a>

相对路径

相对于当前项目的根
<a th:href="@{/show}">相对路径</a>
现对于服务器路径的根,可以跨项目进行访问
<a th:href="@{~/项目名/项目的资源}">相对于服务器的根</a>

在URL中传递参数

在普通格式的url中传递参数

<a th:href="@{/show?id=1&name=zhangsan}">普通URL格式传参</a>
<a:th:href="@{/show(id=1,name=zhansan)}">普通URL格式传参</a>
<a th:href="@{'/show?id='+${id}+'&name='+${name}}">普通URL格式传参</a>
<a th:href="@{/show(id=${id},name=${name})}">普通URL格式传输</a>

在resful格式的URL中传递参数

<a th:href="@{/show/{id}(id=1)}">resful格式参数</a>
<a th:href="@{/show/{id}/{name}(id=1,name=admin)}">resful格式传参</a>
<a th:href="@{/show/{id}(id=1,name=admin)}">restful 格式参数</a>
<a th:href="@{/show/{id}(id=${id},name=${name})}">restful格式传参</a>

在配置文件中配置Thymeleaf

themeleaf前后缀

spring.thymeleaf.prefix=/templates/
spring.thymeleaf.suffix=.html

配置视图模式类型

#html5作为模板的话属性值应该配置为
spring.thmeleaf.mode=HTML5
#默认就是HTML4作为模板
spring.thmeleaf.mode=HTML

thymeleaf的编码

spring.thymeleaf.encoding=utf-8

配置响应类型

#默认是任意类型 "*/*"
spring.thymeleaf.servlet.content-type=text/html
#配置页面缓存,默认是true,一般改为false
spring.thymeleaf.cache=false
原文地址:https://www.cnblogs.com/Ryuichi/p/13448777.html