在《Spring Boot(一):快速開始》中介紹瞭如何使用 Spring Boot 構建一個工程,而且提供 RESTful API ,本節咱們繼續介紹如何使用 Spring Boot 渲染 Web 頁面。javascript
雖然咱們目前擁有許多十分優秀的前端框架,例如: Vue 、 React 等,很是適用於先後端分離的場景,前端能夠獨立部署成爲服務,先後端從物理上徹底進行隔離,下降程序耦合度。可是 Spring Boot 官方依然爲咱們提供了模版引擎用於一些無需先後端分離的場景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推薦使用 Thymeleaf 來作前端模版引擎。打開 start.spring.io/ 能夠看到,在當前Spring Boot 的版本中( 2.1.8.RELEASE ), 官方提供的模版引擎有如下幾種:css
Spring Boot 建議使用這些模版引擎,而並不推薦咱們繼續使用 JSP 。html
Thymeleaf 具體特性以下:前端
這裏咱們先正常構建一個 Spring Boot 工程: spring-boot-thymeleaf ,在 pom.xml 文件中引入 Thymeleaf 的相關依賴,以下:java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
複製代碼
工程的配置文件 application.yml 以下:git
server:
port: 8080
spring:
application:
name: spring-boot-thymleaf
thymeleaf:
# 關閉thymeleaf緩存 開發時使用 不然沒有實時畫面
cache: false
# 檢查模板是否存在,而後再呈現
check-template-location: true
# Content-Type value.
servlet:
content-type: text/html
# 啓用MVC Thymeleaf視圖分辨率
enabled: true
# Template encoding.
encoding: UTF-8
# 關閉嚴格模式
mode: LEGACYHTML5
# Prefix that gets prepended to view names when building a URL.
prefix: classpath:/templates/
# Suffix that gets appended to view names when building a URL.
suffix: .html
mvc:
# 指定靜態資源處理路徑
static-path-pattern: /static/**
view:
suffix: .html
複製代碼
有關 thymeleaf 都寫明瞭註釋,這裏須要注意的有如下幾點:程序員
/static/**
路徑,這裏用於存放咱們的 js 、 css 、圖片等靜態資源。配置通用 404 和 500 頁面,直接在 templates\error
建立對應頁面便可,這裏能夠看一下 Spring Boot 錯誤頁面轉發的源碼 org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver
,以下:github
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
}
return modelAndView;
}
private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
return new ModelAndView(errorViewName, model);
}
return resolveResource(errorViewName, model);
}
複製代碼
能夠看到這裏會根據當前的狀態響應碼轉發到對應的頁面,路由爲 error/**
。筆者這裏簡單建立兩個錯誤頁面,如圖:web
建立測試 Controller ,以下:spring
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(HttpServletRequest request) {
// 構建測試數據
Map<String, Object> map = new HashMap<>();
UserModel userModel = new UserModel();
userModel.setId(1L);
userModel.setName("Spring Boot");
userModel.setAge(18);
map.put("user", userModel);
List<CourseModel> list = new ArrayList<>();
for (int i = 0; i < 2; i++) {
CourseModel courseMode = new CourseModel();
courseMode.setId((long) i);
courseMode.setName("Spring Boot:" + i);
courseMode.setAddress("課程地點:" + i);
list.add(courseMode);
}
map.put("list", list);
map.put("flag", true);
request.setAttribute("data", map);
return "hello";
}
}
複製代碼
在此註冊測試類中,進行數據初始化並輸出至頁面。
src/main/resources/templates
,只須要在這個這個路徑下編寫模版文件便可。Thymeleaf 模版文件以下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello Spring Boot</title>
<link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}">
</head>
<body>
<div class="container">
<div>用戶信息:</div>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">姓名</th>
<th scope="col">年齡</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" th:text="${data.user.id}"></th>
<td th:text="${data.user.name}"></td>
<td th:text="${data.user.age}"></td>
</tr>
</tbody>
</table>
<div>課程信息:</div>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">課程名稱</th>
<th scope="col">課程地點</th>
</tr>
</thead>
<tbody>
<tr th:each="course, iterStat : ${data.list}">
<th scope="row" th:text="${course.id}"></th>
<td th:text="${course.name}"></td>
<td th:text="${course.address}"></td>
</tr>
</tbody>
</table>
<div th:if="${data.flag == true}">若是 flag 爲 true 你將能夠看到這行字:)</div>
</div>
</body>
</html>
複製代碼
Thymeleaf 部分經常使用 th 標籤以下:
關鍵字 | 功能介紹 | 案例 |
---|---|---|
th:id | 替換id | <input th:id="'xxx' + ${collect.id}"/> |
th:text | 文本替換 | <p th:text="${collect.description}">description</p> |
th:utext | 支持html的文本替換 | <p th:utext="${htmlcontent}">conten</p> |
th:object | 替換對象 | <div th:object="${session.user}"> |
th:value | 屬性賦值 | <input th:value="${user.name}" /> |
th:with | 變量賦值運算 | <div th:with="isEven=${prodStat.count}%2==0"></div> |
th:style | 設置樣式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |
th:onclick | 點擊事件 | th:onclick="'getCollect()'" |
th:each | 屬性賦值 | tr th:each="user,userStat:${users}"> |
th:if | 判斷條件 | <a th:if="${userId == collect.userId}" > |
th:unless | 和th:if判斷相反 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> |
th:href | 連接地址 | <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> |
th:switch | 多路選擇 配合th:case 使用 | <div th:switch="${user.role}"> |
th:case | th:switch的一個分支 | <p th:case="'admin'">User is an administrator</p> |
th:fragment | 佈局標籤,定義一個代碼片斷,方便其它地方引用 | <div th:fragment="alert"> |
th:include | 佈局標籤,替換內容到引入的文件 | <head th:include="layout :: htmlhead" th:with="title='xx'"></head> /> |
th:replace | 佈局標籤,替換整個標籤到引入的文件 | <div th:replace="fragments/header :: title"></div> |
th:selected | selected選擇框 選中 | th:selected="(${xxx.id} == ${configObj.dd})" |
th:src | 圖片類地址引入 | <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> |
th:inline | 定義js腳本可使用變量 | <script type="text/javascript" th:inline="javascript"> |
th:action | 表單提交的地址 | <form action="subscribe.html" th:action="@{/subscribe}"> |
th:remove | 刪除某個屬性 | <tr th:remove="all"> 1.all:刪除包含標籤和全部的孩子。2.body:不包含標記刪除,但刪除其全部的孩子。3.tag:包含標記的刪除,但不刪除它的孩子。4.all-but-first:刪除全部包含標籤的孩子,除了第一個。5.none:什麼也不作。這個值是有用的動態評估。 |
th:attr | 設置標籤屬性,多個屬性能夠用逗號分隔 | 好比 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此標籤不太優雅,通常用的比較少。 |
啓動當前工程,打開瀏覽器訪問路徑: http://localhost:8080/hello ,結果如圖: