springboot整合thymeleaf

1 依赖

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

2 application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  thymeleaf:
    cache: false #开启模板缓存默认true
    check-template: true
    check-template-location: true
    servlet:
      content-type: text/html
    enabled: true
    encoding: UTF-8
    excluded-view-names:
    mode: HTML
    prefix: classpath:/templates/
    suffix: .html
  mvc:
    static-path-pattern: /static/**
  web:
    resources:
      static-locations: classpath:/static

3 实体类

public class User {
    private int id;
    private String name;
    private int age;

    public User() {
    }

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

4 controller

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model, HttpSession session) {
        session.setAttribute("name","javavue");
        List<User> list = new ArrayList<>();
        for (int i = 0 ; i < 5; i++) {
            User user = new User();
            user.setId(i);
            user.setName("xiaolan"+i);
            user.setAge(18);
            list.add(user);
        }
        model.addAttribute("users",list);
        User user = new User();
        user.setId(11);
        user.setAge(18);
        user.setName("小白");
        model.addAttribute("user",user);
        return "hello";
    }
}

5.$符号使用

$符号主要是取对象中的数据

<div th:text="${user.id}"></div>
<div th:text="${user.name}"></div>
<div th:text="${user.age}"></div>

6.*符号的使用

*符号也可以取对象中的数据

    <div th:object="${user}">
        <div th:text="*{id}"></div>
        <div th:text="*{name}"></div>
        <div th:text="*{age}"></div>
    </div>

    <div th:text="*{user.id}"></div>
    <div th:text="*{user.name}"></div>
    <div th:text="*{user.age}"></div>

7.@符号的使用

@符号主要是用于引入文件

<a href="test.html" th:href="'http://localhost:8080/blog?id=' + ${blog.id}">博客id</a>
<a href="#" th:href="@{'http://localhost:8080/blog?id=' + ${blog.id}}">博客id</a>
    <!--可以是全路径-->
    <script th:Src="@{http://localhost:8080/hello.js}"></script>
    <!--可以带参数-->
    <script th:Src="@{http://localhost:8080/hello.js(name='yl',age=19)}"></script>
    <!--~代表当前项目-->
    <script th:Src="@{~/hello.js}"></script>
    <!--也可以省略协议-->
    <script th:Src="@{//localhost:8080/hello.js}"></script>

 <img th:src="@{/1.jpg}" th:title="${user.name}" th:alt="${user.name}"/>

8.#符号的使用

#符号主要是根据当前浏览器的语言去相对应的国际化配置文件中取值

<div th:text="#{hello}"></div>

9.集合的遍历

 <div>
        <table border="1px">
            <tr th:each="u,state : ${users}">
                <td th:text="${u.id}"></td>
                <td th:text="${u.name}"></td>
                <td th:text="${u.age}"></td>
                <!--当前的遍历索引,从0开始-->
                <td th:text="${state.index}"></td>
                <!--当前的遍历索引,从1开始-->
                <td th:text="${state.count}"></td>
                <!--集合元素的总个数-->
                <td th:text="${state.size}"></td>
                <!--当前遍历的对象-->
                <td th:text="${state.current}"></td>
                <!--当前遍历是否为奇数次遍历-->
                <td th:text="${state.even}"></td>
                <!--当前遍历是否为偶数次遍历-->
                <td th:text="${state.odd}"></td>
                <!--当前是否为第一次遍历-->
                <td th:text="${state.first}"></td>
                <!--当前是否为最后一次遍历-->
                <td th:text="${state.last}"></td>
            </tr>
        </table>
    </div>

10.thymeleaf如何定义变量

    <!--th:with可以定义变量-->
    <div th:with="num=(100+100/100+90-1)">
        <div th:text="${num}"></div>
    </div>

11.字面量

    <div th:text="'犹在镜中'"></div>
    <div th:text="100"></div>
    <div th:text="true"></div>
    <div th:text="hellovuejava"></div>

12.字符串拼接方式

   <div th:text="'java' + 'js'"></div>
    <div th:text="'java' + ${user.name}"></div>
    <div th:text="|java ${user.name}|"></div>

13.比较运算符

    <div th:with="num=(100+100/100+90-1)">
        <!--第一,第四和第六为true-->
        <div th:text="${num} eq 190"></div>
        <div th:text="${num} ne 190"></div>
        <div th:text="${num} lt 190"></div>
        <div th:text="${num} le 190"></div>
        <div th:text="${num} gt 190"></div>
        <div th:text="${num} ge 190"></div>
    </div>

14.逻辑运算符

    <!--false-->
    <div th:text="9 eq 9 and 8 ne 8"></div>
    <!--true-->
    <div th:text="9 eq 9 or 8 ne 8"></div>
    <!--false-->
    <div th:text="not(9 eq 9 or 8 ne 8)"></div>
    <!--false-->
    <div th:text="!(9 eq 9 or 8 ne 8)"></div>

15.三目运算符

    <div th:with="score=57">
        <div th:text="(${score} ge 60) ? '及格' : '不及格'"></div>
    </div>

16.分支结构,th:if,th:unless,th:switch,th:case

    <div>
        <table border="1px">
            <!--th:if只显示偶次数出现的数据,th:unless则是取反-->
            <tr th:each="u,state : ${users}" th:if="${state.odd}">
                <td th:text="${u.id}"></td>
                <td th:text="${u.name}"></td>
                <td th:text="${u.age}"></td>
                <!--当前的遍历索引,从0开始-->
                <td th:text="${state.index}"></td>
                <!--当前的遍历索引,从1开始-->
                <td th:text="${state.count}"></td>
                <!--集合元素的总个数-->
                <td th:text="${state.size}"></td>
                <!--当前遍历的对象-->
                <td th:text="${state.current}"></td>
                <!--当前遍历是否为奇数次遍历-->
                <td th:text="${state.even}"></td>
                <!--当前遍历是否为偶数次遍历-->
                <td th:text="${state.odd}"></td>
                <!--当前是否为第一次遍历-->
                <td th:text="${state.first}"></td>
                <!--当前是否为最后一次遍历-->
                <td th:text="${state.last}"></td>
            </tr>
        </table>
    </div>

<!--switch case语句-->
    <div>
        <table border="1px">
            <tr th:each="u,state : ${users}">
                <td th:text="${u.id}"></td>
                <td th:text="${u.name}"></td>
                <td th:text="${u.age}"></td>
                <!--当前的遍历索引,从0开始-->
                <td th:text="${state.index}"></td>
                <!--当前的遍历索引,从1开始-->
                <td th:text="${state.count}"></td>
                <!--集合元素的总个数-->
                <td th:text="${state.size}"></td>
                <!--当前遍历的对象-->
                <td th:text="${state.current}"></td>
                <!--当前遍历是否为奇数次遍历-->
                <td th:text="${state.even}"></td>
                <!--当前遍历是否为偶数次遍历-->
                <td th:text="${state.odd}"></td>
                <!--当前是否为第一次遍历-->
                <td th:text="${state.first}"></td>
                <!--当前是否为最后一次遍历-->
                <td th:text="${state.last}"></td>
                <td th:switch="${state.odd}">
                    <span th:case="true">偶数</span>
                    <span th:case="*">基数</span>
                </td>
            </tr>
        </table>
    </div>

17.thymeleaf的一些常用的内置对象

<!--thymeleaf的一些常用的内置对象-->
    <!--session对象-->
    <div th:text="${#session.getAttribute('name')}"></div>
    <!--lists对象-->
    <div th:text="${#lists.size(users)}"></div>
    <!--execInfo对象-->
    <div th:text="${#execInfo.getProcessedTemplateName}"></div>

18.内联

<!--内联-->
    <!--其实取对象里的值还有以下这两种方式-->
    <div>hello [[${user.name}]]</div>
    <div>hello [(${user.name})]</div>
    <hr/>

    <!--如下,第一种方式对内容进行转义了,第二种方式没有对内容进行转义-->
    <div th:with="str='jq <b>a better language</b>'">
      <div>[[${str}]]</div>
       <div>[(${str})]</div>
   </div>

    <script th:inline="javascript">
        var name = [[${user.name}]]
        console.log(name)
    </script>

19总结

Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。

它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。

由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。

Thymeleaf 支持在 js 中直接获取 Model 中的变量。例如,在 IndexController 中有一个变量 username :

这个功能算是 Thymeleaf 的特色之一吧。

手动渲染
前面我们说的是返回一个 Thymeleaf 模板,我们也可以手动渲染 Thymeleaf 模板,这个一般在邮件发送时候有用,例如我在 resources/templates 目录下新建一个邮件模板,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息如下:</p>
<table border="1">
    <tr>
        <td>职位</td>
        <td th:text="${position}"></td>
    </tr>
    <tr>
        <td>薪水</td>
        <td th:text="${salary}"></td>
    </tr>
</table>
</body>
</html>

这一个 HTML 模板中,有几个变量,我们要将这个 HTML 模板渲染成一个 String 字符串,再把这个字符串通过邮件发送出去,那么如何手动渲染呢?

@Autowired
TemplateEngine templateEngine;
@Test
public void test1() throws MessagingException {
Context context = new Context();
context.setVariable(“username”, “javaboy”);
context.setVariable(“position”, “Java工程师”);
context.setVariable(“salary”, 99999);
String mail = templateEngine.process(“mail”, context);
//省略邮件发送
}
渲染时,我们需要首先注入一个 TemplateEngine 对象,这个对象就是在 Thymeleaf 的自动化配置类中配置的(即当我们引入 Thymeleaf 的依赖之后,这个实例就有了)。
然后构造一个 Context 对象用来存放变量。
调用 process 方法进行渲染,该方法的返回值就是渲染后的 HTML 字符串,然后我们将这个字符串发送出去。
这是 Spring Boot 整合 Thymeleaf 的几个关键点,关于 Thymeleaf 这个页面模板本身更多的用法,大家可以参考 Thymeleaf 的文档:https://www.thymeleaf.org。

@RequestMapping("/test")
    public String test(ModelMap map){
        User u = new User();
        u.setName("haozz");
        u.setAge(24);
        u.setPassword("qwerty");
        u.setBirthday(new Date());
        u.setDesc("<font color='green'><b>talk is cheap, show me the code</b></font>");

        User u1 = new User();
        u1.setName("nico robin");
        u1.setAge(35);
        u1.setPassword("qwerty");
        u1.setBirthday(new Date());
        u1.setDesc("<font color='green'><b>talk is cheap, show me the code</b></font>");

        User u2 = new User();
        u2.setName("nami");
        u2.setAge(27);
        u2.setPassword("qwerty");
        u2.setBirthday(new Date());
        u2.setDesc("<font color='green'><b>talk is cheap, show me the code</b></font>");

        List<User> userList = new ArrayList<>();
        userList.add(u);
        userList.add(u1);
        userList.add(u2);
        map.addAttribute("user",u);
        map.addAttribute("userList",userList);
        return "thymeleaf/test/test";
    }

    @PostMapping("/postform")
    public String postform(User u){
        System.out.println(u.getName());
        return "redirect:/th/test";
    }
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:method="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    用户姓名:<input th:id="${user.name}" th:name="${user.name}" th:value="${user.name}"/>
    <br/>
    用户年龄:<input th:value="${user.age}"/>
    <br/>
    用户生日:<input th:value="${user.birthday}"/>
    <br/>
    用户生日:<input th:value="${#dates.format(user.birthday,'yyyy-MM-dd')}"/><!--时间格式转换-->
    <br/>
</div>
<br/>
<div th:object="${user}"><!--定义一个对象,指定为user,下面的user都可以省略不写-->
    用户姓名:<input th:id="*{name}" th:name="*{name}" th:value="*{name}"/>
    <br/>
    用户年龄:<input th:value="*{age}"/>
    <br/>
    用户生日:<input th:value="*{#dates.format(birthday,'yyyy-MM-dd')}"/><!--时间格式转换-->
    <br/>
</div>
<br/>
th:text与th:utext<br/>
<span th:text="${user.desc}"></span><!--th:text 不会进行转译-->
<br/>
<span th:utext="${user.desc}"></span><!--th:utext 会进行转译-->
<br/>
<br/>
URL:<br/>
<a th:href="@{http://www.haozz.top:18158}" th:target="_blank">多多关照</a>
<br/>
<br/>
<form th:action="@{/th/postform}" th:object="${user}" th:method="post"><!--表单提交-->
    <input type="text" th:field="*{name}"/><!--th:field="*{name}"相当于id="name" name="name" value="具体的name值"-->
    <input type="submit"/>
</form>
<br/>
<br/>
<div th:if="${user.age lt 25}">young</div><!--lt 小于-->
<div th:if="${user.age ge 25}">old</div><!--ge 大于等于-->
<br/>
<br/>
<table>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>备注</th>
        <th>生日</th>
    </tr>
    <tr th:each="person:${userList}"><!--循环userList,以person作为形参-->
        <td th:text="${person.name}"></td>
        <td th:text="${person.age}"></td>
        <td th:text="${person.age ge 25} ? old : young"></td>
        <td th:text="${#dates.format(person.birthday,'yyyy-MM-dd hh:mm:ss')}"></td>
    </tr>
</table>
<br/>
<br/>
<div th:switch="${user.name}">
    <p th:case="'haozz'">最帅的</p>
    <p th:case="'nico robin'">妮可罗宾</p>
    <p th:case="'nami'">娜美</p>
</div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值