SpringBoot--Thymeleaf入門使用

1、概述javascript

今天學習到了SpringBoot中的WEB開發,SpringBoot提供了spring-boot-stater-web爲web開發給予支持,它裏面內嵌瞭如下依賴:css

<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下,以下圖所示:html

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.htmljava

2、經過一個簡單的實例舉例說明jquery

本例以Thymleaf爲模板引擎,從服務端獲取數據並展現在頁面。web

第一步:建立一個Javabean用來在模板頁面展現數據person.javaspring

/**
 * 模板數據
 */
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;
    }
}

 第二步:建立Controllerjson

@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。bootstrap

第三步:建立頁面index.html獲取數據tomcat

<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模板的使用,這個例子中用到的主要知識點有如下幾個:

一、引入Thymeleaf

  • 經過<html xmlns:th="http://www.thymeleaf.org">命名空間,將靜態頁面轉換爲動態視圖。須要進行動態處理的元素須要使用"th:"做爲前綴;
  • 經過「@{}」引用web靜態資源,如js、css、image等文件;

二、訪問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中的數據

三、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.*}來獲取對象的屬性了。

四、數據判斷

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

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

Thymeleaf還支持>、<、>=、<=、==、!=等做爲條件比較。

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

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

二、<button class="btn btn-info" th:onclick="getName([[${person.userName}]],[[${person.age}]],this);">獲取用戶信息</button>

這兩句都是在HTML中調用js函數時傳遞model數據的寫法,可是第一種會報錯!!!

相關文章
相關標籤/搜索