1. 程式人生 > >SpringBoot--Thymeleaf入門使用

SpringBoot--Thymeleaf入門使用

一、概述

今天學習到了SpringBoot中的WEB開發,SpringBoot提供了spring-boot-stater-web為web開發給予支援,它裡面內嵌了以下依賴:

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.1.0.RELEASE</
version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <version>2.1.0.RELEASE</version> <scope>
compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.1.0.RELEASE</version> <scope>compile</scope> </
dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.2.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.2.RELEASE</version> <scope>compile</scope> </dependency> </dependencies>

主要是Tomcat和Spring MVC的依賴,而web相關的自動配置則在spring-boot-autoconfigure.jar的org.springframework.boot.autoconfigure.web下,如下圖所示:

springboot提供的模板引擎有:FreeMarker[fri'mɑːkə(r)]、Groovy['ɡruvi]、Thymeleaf[taɪm'lif]、Velocity[və'lɑsəti]、Mastache['mʌstæʃ],為了準確讀出,我加了它們的音標,springboot中推薦使用Thymeleaf作為模板引擎,因為它提供了完美的SpringMVC的支援。關於Thymleaf的語法可以通過官網進行學習https://www.thymeleaf.org/doc/articles/thymeleaf3migration.html

二、通過一個簡單的例項舉例說明

本例以Thymleaf為模板引擎,從服務端獲取資料並展示在頁面。

第一步:建立一個Javabean用來在模板頁面展示資料person.java

/**
 * 模板資料
 */
public class Person {

    private String userName;

    private int age;

    public Person(String userName, int age) {
        this.userName = userName;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

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

 第二步:建立Controller

@Controller
@SpringBootApplication
public class WebdemoApplication {

    @RequestMapping("/")
    public String index(Model model) {
        Person person = new Person("張三", 26);

        List<Person> people = new ArrayList<>();
        Person p1 = new Person("李四", 27);
        Person p2 = new Person("王五", 27);
        Person p3 = new Person("趙六", 27);
        people.add(p1);
        people.add(p2);
        people.add(p3);

        model.addAttribute("singlePerson", person);
        model.addAttribute("people", people);
        return "index";
    }

    public static void main(String[] args) {
        SpringApplication.run(WebdemoApplication.class, args);
    }
}

上面紅色加粗部分是將一個使用者個一個使用者列表設定到model中,傳給前頁面index.html,所以接下來再建立一個index.html。

第三步:建立頁面index.html獲取資料

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link th:href="@{bootstrap/css/bootstrap.css}" rel="stylesheet">
    <link th:href="@{bootstrap/css/bootstrap-theme.css}" rel="stylesheet">
    <link th:href="@{css/demo.css}" rel="stylesheet">
    <title>Title</title>
</head>
<body>

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">訪問model</h3>
    </div>
    <div class="panel-body">
        <label>姓名:</label><span th:text="${singlePerson.userName}"/>
        <label>年齡:</label><span th:text="${singlePerson.age}"/>
    </div>
</div>

<div th:if="${not #lists.isEmpty(people)}">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">訪問列表</h3>
        </div>
    </div>
    <div class="panel-body">
        <ul class="list-group">
            <li class="list-group-item">
                <span class="span1">使用者名稱</span>
                <span class="span1">密碼</span>
                <span class="span3">操作</span>
            </li>
            <li class="list-group-item" th:each="person:${people}">
                <span class="span2" th:text="${person.userName}"></span>
                <span class="span2" th:text="${person.age}"></span>
                <!--<button class="btn" th:onclick="'getName(\''+[[${person.userName}]]+'\');'">獲取姓名</button>-->
                <button class="btn btn-info" th:onclick="getName([[${person.userName}]],[[${person.age}]],this);">
                    獲取使用者資訊
                </button>
            </li>
        </ul>
    </div>
</div>
<script th:src="@{jquery-1.8.3.min.js}" type="text/javascript"></script>
<script th:src="@{bootstrap/js/bootstrap.js}" type="text/javascript"></script>
<script th:inline="javascript">
    var single = [[${singlePerson}]];
    console.log(single.userName + "--" + single.age);

    function getName(name, age, obj) {
        var html = "My name is " + name + " and i am " + age + " years old.";
        $(obj).parent().append(html);
    }
</script>
</body>
</html>

建立完之後的目錄結構如下:

紅色方框中的是web檔案的目錄,都放在resource目錄下了。至此,所有檔案建立完成,頁面訪問效果如下:

這是一個簡單的入門例子,主要是熟悉一下Thymeleaf模板的使用,這個例子中用到的主要知識點有以下幾個:

1、引入Thymeleaf

  • 通過<html xmlns:th="http://www.thymeleaf.org">名稱空間,將靜態頁面轉換為動態檢視。需要進行動態處理的元素需要使用"th:"作為字首;
  • 通過“@{}”引用web靜態資源,如js、css、image等檔案;

2、訪問model中的資料

  • 通過${}訪問:如這句<span class="span2" th:text="${person.userName}"></span>,通過“${}” 獲取
  • 通過[[${}]]訪問:如下面這句
<button class="btn btn-info" th:onclick="getName([[${person.userName}]],[[${person.age}]],this);">
    獲取使用者資訊
</button>

這種方式一般用來在javascript中訪問model中的資料

3、model中的資料迭代

使用th:each來迴圈迭代,如

<li class="list-group-item" th:each="person:${people}">
                <span class="span2" th:text="${person.userName}"></span>
                <span class="span2" th:text="${person.age}"></span>
                <button class="btn btn-info" th:onclick="getName([[${person.userName}]],[[${person.age}]],this);">
                    獲取使用者資訊
                </button>
</li>

person作為迭代元素來使用,這樣在下面的元素中就可以通過${person.*}來獲取物件的屬性了。

4、資料判斷

<div th:if="${not #lists.isEmpty(people)}">
    .........省略......
</div>

上面程式碼中,在div內部使用列表資料之前要先判斷列表是否為空,就用了${not #list.isEmpty(people)}這樣的句式。

Thymeleaf還支援>、<、>=、<=、==、!=等作為條件比較。

以上就是這個入門例項中用到的Thymeleaf中的相關知識,需要注意的是下面這兩句:

1、<button class="btn" th:onclick="'getName(\''+[[${person.userName}]]+'\');'">獲取姓名</button>

2、<button class="btn btn-info" th:onclick="getName([[${person.userName}]],[[${person.age}]],this);">獲取使用者資訊</button>

這兩句都是在HTML中呼叫js函式時傳遞model資料的寫法,但是第一種會報錯!!!