如何使用SpringBoot快速搭建Thymeleaf

樓主是個小白(剛工作的大三實(shí)習(xí)生)輕點(diǎn)吐槽
下面介紹一下Thymeleaf
Thymeleaf是適用于Web和獨(dú)立環(huán)境的現(xiàn)代服務(wù)器端Java模板引擎。
Thymeleaf的主要目標(biāo)是為您的開發(fā)工作流程帶來優(yōu)雅的自然模板?-HTML可以在瀏覽器中正確顯示,也可以作為靜態(tài)原型工作,從而可以在開發(fā)團(tuán)隊(duì)中加強(qiáng)協(xié)作。
Thymeleaf擁有適用于Spring Framework的模塊,與您喜歡的工具的大量集成以及插入您自己的功能的能力,對于現(xiàn)代HTML5 JVM Web開發(fā)而言,Thymeleaf是理想的選擇-盡管它還有很多工作要做。
總的說,大概可能是SpringBoot對Jsp頁面的一些原因,反正很少看到Jsp的頁面啦。
首先新建一個SpringBoot項(xiàng)目,樓主用的是IDEA(個人比較推薦吧,反正用的比Eclipse爽一點(diǎn))。在IDEA中直接new,project,選擇SpringInitializr,然后next,等待一會把用到的包導(dǎo)入進(jìn)來。然后下一步定義項(xiàng)目的名字和路徑名。

輸入完成后next,然后就到了選擇需要的模板頁了。選擇你需要的模板,也可以后期手動導(dǎo)入

新建好項(xiàng)目后等待項(xiàng)目目構(gòu)建完成。打開Pom.xml文件在denpendencies中添加如下代碼段。
<dependency>
? ?<groupId>org.springframework.boot</groupId>
? ?<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在更改pom文件后編輯器會提示選擇ImportChanges就好了。
然后你就可以看到引入好的thymeleaf啦。

這個是SpringBoot為我們配置的thymeleaf然后我們就可以使用thymeleaf模板了。

(這里省略了配置SpringBoot啟動項(xiàng)的-------------網(wǎng)上有很多文章這里不帶大家配置了)
下面2步配置一個基本的thymeleafHelloword
1.配置一個Controller,
@Controller
public class UserController {
@RequestMapping(value = "testThymeleaf")
? ?public String testThymeleaf(Model model){
? ? ? ?//model.addAttribute("username","admin");(這句話是存儲數(shù)據(jù)的)
? ? ? ?return "success";
? ?}
}
2.在項(xiàng)目根路徑也就是resources路徑下新建templates并放入一個success.html
<!DOCTYPE html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<title>success</title>
</head>
<body>
<!--<h3 th:text="${username}"></h3>接收數(shù)據(jù) -->
<h3>成功!</h3>
</body>
</html>
運(yùn)行項(xiàng)目一個簡單的thymeleafHelloword就搭建好了。
下面說幾點(diǎn)注意的東西。
thymeleaf在3.0之前語法非常嚴(yán)謹(jǐn),html的標(biāo)簽不</>可能會引發(fā)啟動錯誤,這個時候需要升級thymeleaf的版本,在Pom文件中更改properties標(biāo)簽下的內(nèi)容
<properties>
? ?<!-- 指定java版本8 -->
? ?<java.version>1.8</java.version>
? ?<!--更改Thymeleaf版本-->
? ?<Thymeleaf.version>3.0.2.RELEASE</Thymeleaf.version>
? ?<Thymeleaf-layout-dialect.version>2.1.1</Thymeleaf-layout-dialect.version>
</properties>
不要隨便使用合成注解,例如@RestController,一定要搞清楚和@Controller的區(qū)別否則可能會出現(xiàn)意想不到的錯誤(比如樓主直接返回了個字符串,還找了半個小時并從頭配置了一邊)