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數據的寫法,但是第一種會報錯!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM