1. 程式人生 > >SpringBoot教程(九)springboot整合Thymeleaf

SpringBoot教程(九)springboot整合Thymeleaf

一.Thymeleaf簡單整合

  1.專案結構

   

  2.pom依賴

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.spf.demo</groupId>
    <artifactId>spf-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

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

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

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

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

    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

  3.application配置檔案

###Tomcat Config
server.port=8080
server.tomcat.uri-encoding=UTF-8

####DataSource Config
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lpinfo?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

###SPBdefaultLoggin Config
logging.level.root=info
#設定檔案,如會在該專案下生成日誌檔案
logging.file=spf_demo.log
#設定檔案會在某個資料夾下生成檔案寫入日誌
#logging.path=/usr/log/spf_demo.log

####thymeleaf Config
# 模板格式
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false

  4.控制層

package com.spf.demo.app;

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


/**
 * Hello world!
 */
@Controller
@RequestMapping("/app")
public class App {

    @RequestMapping("/thymeleaf")
    public String thymeleaf(ModelMap map) {
        map.addAttribute("user", "zhangsan");
        map.addAttribute("title", "thymeleaf 模板測試");
        return "login";
    }

}

 5.index頁 放在static檔案下 預設訪問到

6.index請求控制層-->跳轉登入頁面

7.執行結果

二.Thymeleaf語法語法講解

  1.語法圖解

表示式語言

Thymeleaf模板引擎在進行模板渲染時,還會附帶一個Context存放進行模板渲染的變數,在模板中定義的表示式本質上就是從Context中獲取對應的變數的值:

<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

URL

URL在Web應用模板中佔據著十分重要的地位,需要特別注意的是Thymeleaf對於URL的處理是通過語法@{...}來處理的。Thymeleaf支援絕對路徑URL:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

另外,如果需要Thymeleaf對URL進行渲染,那麼務必使用th:hrefth:src等屬性,下面是一個例子

<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

運算子

在表示式中可以使用各類算術運算子,例如+, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

迴圈

渲染列表資料是一種非常常見的場景,例如現在有n條記錄需要渲染成一個表格<table>,該資料集合必須是可以遍歷的,使用th:each標籤:

 <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
  </table>

條件求值

If/Unless

Thymeleaf中使用th:ifth:unless屬性進行條件判斷,下面的例子中,<a>標籤只有在th:if中條件成立時才顯示:

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

Switch

Thymeleaf同樣支援多路選擇Switch結構:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

Utilities

為了模板更加易用,Thymeleaf還提供了一系列Utility物件(內置於Context中),可以通過#直接訪問:

  • #dates
  • #calendars
  • #numbers
  • #strings
  • arrays
  • lists
  • sets
  • maps
  • ...

下面用一段程式碼來舉例一些常用的方法: