SpringBoot十二:模板引擎之Thymeleaf

模板引擎介紹

常見的模板引擎下:JSP、Velocity、Freemarker、Thymeleaf(SpringBoot推薦)

 

執行過程:模板(Template)+數據(Data)====交給模板引擎(TemplateEngine)====out寫出去

 

SpringBoot推薦的Thymeleaf模板引擎特點:語法簡單,功能更強大

 

SpringBoot Thymeleaf引擎模板使用

1、引入Thymeleaf模板引擎maven依賴spring-boot-starter-thymeleaf

2、只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染

3、Thymeleaf語法

  • 頁面導入xmln:th="http://www.thymeleaf.org"eleaf.org"
  • th:text="${}" 
  • th:href="@{/url}"       其中@表示http://localhost:port/項目名
  • th:src="@{/url}"

4、開發期間模板引擎頁面修改以後,要實時生效

  • 禁用模板引擎的緩存,在application.properties配置spring.thymeleaf.cache=false
  • 頁面修改完成以後,ctrl+f9:重新編譯(IDEA環境)

 

SpringBoot Thymeleaf引擎模板實戰

1、引入maven依賴(可以到SpringBoot官網找start啓動器)

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

2、編寫Controller控制類(自動生成的SpringBoot)

package com.xue.springbootweb.controller;

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

import java.util.Date;

/**
 * @Description
 * @Author xuexue
 * @Date 2019/9/28 17:25
 */
@Controller
public class TestController {

    @RequestMapping(value = "/login")
    public String toHelloWorld() {
        return "login";
    }

}

3、在templates下創建編寫login文件(templates由模板引擎自動渲染)

頭部引入,編寫html時,就會有提示thymeleaf語法信息

xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" th:value="我是內容" />
<span th:text="我是範圍"></span>
</body>
</html>

運行結果

 

 

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