SpringBoot:thymeleaf粗解

thymeleaf 百里香的葉片            

thymeleaf可以支持動態頁面,即模板+數據。如下,html中的h1標籤並不寫死,而是可以在mode中動態設置的。

SpringBoot在pom.xml中引入該引擎時,可以不用指定版本號,其他的也不用指定,自動會配置好。 SpringBoot通過一個個×××AutoConfiguration實現自動裝配,thymeleaf也有一個thymeleafAutoConfiguration,如果要修改默認的屬性值,那麼在.properties文件中通過prefix+屬性的方式修改。

下面以實例展示thymeleaf模板+數據的用法。

1.新建一個springBoot web工程

2.在pom.xml中引入thymeleaf依賴

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

3.在thymeleafAutoconfiguration中,可以發現,其默認格式是.html,默認放置在templates目錄下。

    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";

所以接下來在templates目錄下新建一個result.html的thymeleaf文件,進入thymeleaf官網的tutorial中,將提供的簡單示例代碼複製進result.html中。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head>
<body>
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
</body>
</html>

稍作修改,去掉meta和link,保留body並且將#{home.welcome}修改成${welcome}

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Good Thymes Virtual Grocery</title>
</head>
<body>
    <p th:text="${welcome}">Welcome to our grocery store!</p>
</body>
</html>

4.新建一個controller,響應請求。

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class BootController {

    @RequestMapping("/request")
    public String request(Map<String,Object> map){
        map.put("welcome","WelcomeToThymeleaf");//給${welcome}賦值welcomeToThymeleaf
        return "result";
    }
}

結果:<p th:text="${welcome}">Welcome to our grocery store!</p>中的Welcome to our grocery store!將被替換成爲${welcome}的內容。

 

目錄結構:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章