SpringBoot引入並使用Thymeleaf


------------恢復內容開始------------

一、Thymeleaf引入

1.maven引入starter

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

2.切換版本

由於SpringBoot的starter集成的thymeleaf2,我們需要切換成thymeleaf3,但是thymeleaf3需要layout2,所以需要加下面的版本修改

  <properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>

 

3.完整maven貼上

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         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>

    <groupId>muyer-springboot</groupId>
    <artifactId>quickStart</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

 

二、Thymeleaf使用

1.創建templates文件夾

查看源碼,如下圖,我們只需要把HTML頁面放在classpath:/templates/,thymeleaf就能夠渲染了

 

 2.創建HTML

創建的html頁面需要引入thymeleaf的名稱空間,才會有提示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <h1>hello Thymeleaf</h1>
    <div th:text="${name}"></div>
    <div th:each="item:${subject}">
        <div th:text="${item}"></div>
        [[${item}]]
    </div>
</body>
</html>

3.創建controller

@Controller
public class HelloController {
    @RequestMapping(value = "helloThymeleaf")
    public String hello(Map<String,Object> map){
        map.put("name","yj");
        map.put("subject", Arrays.asList("math","phy"));
        return "hello";
    }
}

4.啟動測試,訪問

三、Thymeleaf語法

 


免責聲明!

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



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