1.添加Thymeleaf和Webjars依賴
thymeleaf模板引擎依賴
<groupId>org.springframework.boot</groupId> 3
<artifactId>spring-boot-starter-thymeleaf</artifactId> 4
</dependency>
Webjars模板引擎依賴
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
2.代碼目錄結(jié)構(gòu)

1.png
resources下static?件夾存放images、css、js等靜態(tài)資源
templates存放Thymeleaf模板??
3.Controller層代碼寫法
package com.example.quickstart.controller;
import com.example.quickstart.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
@Controller
public class IndexController {
//注入了一個Student類的對象,被Spring容器托管——bean
@Resource
private Student student;
//Get請求映射
@GetMapping("index")
public String index(ModelMap map) {
student.setName("Tom");
student.setAge(20);
student.setMale("男");
//將模型加入視圖
map.addAttribute("student",student);
return "index";
}
}
4. html??頭部添加thymeleaf名稱空間聲明
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主頁</title>
</head>
<body>
<p th:text="${stduent.name}"></p>
</body>
</html>
5. 通過Webjars引?靜態(tài)資源
Web前端使?了越來越多的JS或CSS,?般情況下,我們是將這些Web資源拷?到
Java的?錄下,或者通過CDN引?,通過??進?管理,這種?式容易導(dǎo)致?件混亂、
版本不?致等問題。
WebJars是將這些通?的Web前端資源打包成Java的Jar包,然后借助Maven?具對
其管理,保證這些Web資源版本唯?性,升級也?較容易。關(guān)于Webjars資源,有?個
專?的?站http://www.webjars.org/,我們可以到這個?站上找到??需要的資源,
在??的?程中添加?maven依賴,即可直接使?這些資源了。
如:?個使?bootstrap的Webjars的例?:
<html xmlns:th="http://www.thymeleaf.org">
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<title>歡迎頁面</title>
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<body>
<div class="alert alert-success">
<p th:text="${info}"></p>
</div>
</div>