11. 從零開始學(xué)springboot-整合thymeleaf

前言

上一節(jié)使用了"過時(shí)"的jsp技術(shù),這一節(jié)我們來使用springboot推薦的模板thymeleaf技術(shù)。

創(chuàng)建項(xiàng)目

使用IDEA創(chuàng)建springboot項(xiàng)目,直接勾選web和thymeleaf依賴


1.png

查看依賴

2.png

添加配置

application.yml:

spring:
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    ##關(guān)閉緩存
    cache: false

添加模板

在resources的templates下創(chuàng)建index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head>
    <meta charset="utf-8"/>
</head>
<body>
<span th:text="'yes, ' + ${name} + '!'"></span>
</body>
</html>

注意,這里模板內(nèi)注入了個(gè)變量"name",模板都是使用"${變量名}"這種方式注入變量的。

完善

目錄結(jié)構(gòu)

3.png

controller/IndexController:

package com.mrcoder.sbthymeleaf.controller;


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

@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public String index(Model model){
        //注入name變量到模板
        model.addAttribute("name", "hello world");
        return "index";
    }
}

訪問

4.png

關(guān)于thymeleaf的更多語法請自行去看官方文檔哦。

項(xiàng)目地址

https://github.com/MrCoderStack/SpringBootDemo/tree/master/sb-thymeleaf

https://gitee.com/MrCoderStack/SpringBootDemo/tree/master/sb-thymeleaf

請關(guān)注我的訂閱號

訂閱號.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容