前言
上一節(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