第9章 整合前端

通過前面的項目我們已經瞭解了很多和微服務項目相關的知識點,但是這些服務都沒有界面,本章我們將爲customer微服務項目添加一個界面,展示個別用戶的詳情。

注意:雖然微服務化後的系統都提倡前後端分離,但是傳統的前端模版還是很有用的,本書將在後面對前後端分離進行專門講解。

9.1 認識Thymeleaf

Spring Boot作爲一個快速開發框架,本身對前端模板的支持是很完善的,比如Freemarker、Velocity以及Thymeleaf等。其中Thymeleaf對Html原型的良好支持讓它備受開發人員喜歡。

Thymeleaf官網首頁有如下一段話,很好地介紹了Thymeleaf這個模板的優點,具體可參看:Thymeleaf官網地址:https://www.thymeleaf.org

Thymeleaf是作爲一個服務端的Java模板引擎,雖然他的代碼仍然和後臺程序寫在一個工程裏面,和傳統的JSP相似,但是在靜態模式下,它的頁面是可以正常展示的,可以讓前端開發人員更方便地進行頁面調整,在一定程度上將前端頁面的工作分離開來。

9.2 引入Thymeleaf

在正式編寫代碼引入Thymeleaf之前,首先要了解到Spring Boot項目中模板的路徑爲:src/main/resources/templates。這個路徑可以修改,但是一般我們使用默認的足矣。

和Spring Boot的其他集成相同,Thymeleaf也有自己的Starter包。在pom.xml中添加下面代碼,向customer微服務添加Thymeleaf支持,完成一個簡單的用戶信息展示頁。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

創建UserViewController.java文件,添加如下代碼,完成單個用戶的跳轉:

package cn.com.hanbinit.customer.controller;

import cn.com.hanbinit.customer.model.User;
import cn.com.hanbinit.customer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller // 這裏使用@Controller註解,是因爲這個文件中的接口需要進行頁面跳轉
public class UserViewController {

    @Autowired
    private UserService userService;

    /**
    * 根據用戶Id現實用戶信息
    * @param userId
    * @return
    */
    @GetMapping("/user/{userId}")
    public String userInfo(@PathVariable Integer userId, ModelMap map){

        User user = userService.getUserById(userId);
        // 將查詢的user對象放入ModelMap中
        map.put("user", user);
        // 下面一行直接返回thymeleaf中的文件名(不帶前綴)
        return "user_detail";
    }

}

同時,在resources/templates目錄下添加文件user_detail.html。內容如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

    <head>
        <meta charset="UTF-8">
        <title>用戶基本信息</title>
    </head>

    <body>
        用戶ID:<span th:text="${user['id']}">id</span> <br>
        用戶名稱:<span th:text="${user['nickname']}">name</span> <br>
        用戶年齡:<span th:text="${user['age']}">age</span>
    </body>

</html>

啓動服務,如圖9.1所示,通過接口http://localhost:8001/users查看當前表中已經存在的所有用戶信息。

c122a17538c78ce11a4dfd764f515734.png
圖9.1 當前已經存在的所有用戶信息

 

我們嘗試向本節新加接口中傳參3,通過訪問接口http://localhost:8001/users/3可以看到如圖9.2的結果。

6e3d952240fe07312de29045b5f37ecc.png
圖9.2 Thymeleaf輸出結果

 

到這裏爲止,我們在customer微服務中引入了Thymeleaf,並且實現了根據userId展示用戶信息的功能。這裏我們對Thymeleaf的語法不做過多講解,感興趣的同學可以直接到官網查閱(Thymeleaf
官方文檔:https://www.thymeleaf.org/documentation.html)。

9.3 小結

本文通過一個很簡單的例子,演示瞭如何在Spring Boot項目中引入Thymeleaf模板,並且通過簡單的編碼實現了根據userId格式化輸出用戶信息的接口。

除了Thymeleaf,Spring Boot對freemarker、Velocity以及JSP都有比較好的支持,但是因爲JSP在嵌入式servlet容器時有部分限制,所以官方不建議使用。

在可執行的Spring Boot jar中,JSP是不能生效的,另外,Undertow不支持JSP。更詳細的說明可以自行查詢官方文檔。

其實多說一句,JSP這個東西如果沒有必要, 就不要深入學習了。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章