Spring Boot從入門到精通-頁面模板

在web大行其道的今天,有了接口之後最好的展示方式就是用頁面。而Spring Boot中對於模板頁有良好的支持。下面我們來介紹Spring Boot推薦的模板 thymeleaf。

  • 首先在pom.xml中加入依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

需要注意,爲了讓thymeleaf識別一個模板,你必須使用下面的html頭標籤:

<html xmlns:th="http://www.thymeleaf.org">
...
</html>
  • 引入javascript
<script th:inline="javascript">
 var article = [[${article}]];
...
</script>

首先我們在resources目錄下新建templates文件夾和static文件夾。
關於這兩個文件夾,在Spring Boot中,靜態資源默認是訪問resources下的static文件夾,動態html資源默認是訪問resourcess目錄下的templates。當然這兩個默認路徑可以再application.yml中進行配置,一般我們都使用默認路徑。由於我們需要的是一個由Spring Boot生成的動態模板頁,因此在templates下新建demo1.html。
由於動態模板頁需要先經過後臺接口,然後才返回一個html頁面到前端,因此在controller文件夾下新建ThymeleafController.java。

@Controller
public class ThymeleafController {

    @GetMapping("/thymeleaf")
    public String testMapper() {
        return "demo1";
    }
}

注意我們使用了@Controller而不是@RestController。具體的區別請查看Spring Boot從入門到精通-註解詳解
寫了一個路徑爲/thymeleaf的接口,該接口直接返回了一個值爲我們需要返回的html的名字的字符串。
目錄結構如下:

  • 引入普通文本:th:text
<p th:text="'你好,thymeleaf~~~'"> hello world!</p>
  • 引入變量: ${變量名}
    變量名由後臺傳遞給前端,因此需要修改接口。
@GetMapping(value = "thymeleaf")
   public String articleInfo(Model model) {
       model.addAttribute("data", "i'm a data");
       User user = new User();
       user.setUserId(1);
       user.setUserName("admin");
       user.setPassword("123");
       user.setPhone("110");
       model.addAttribute("user", user);
       return "demo1";
   }

在方法上新增了一個入參model,通過model傳遞前端需要的值。而這個“data”就是前端的變量名。

<h1 th:text="'hello,' + ${data} + '!'">測試文本!</h1>
<h1 th:text="'標號:'+  ${user.userId}">id</h1>

另外也可以在JavaScript中直接使用對象接收。

  • 消息表達式:#{key}
    消息表達式允許你再模板頁面上讀取消息源裏面的靜態內容,消息源可以是配置文件,數據庫等,消息配置文件實際就是一個properties文件,文件內容爲key=value形式的鍵值對。
    如果你使用spring boot的默認配置,那麼配置文件的名稱爲messages.properties,他必須放在resource根目錄下,這樣thymeleaf才能找到。
    消息表達式常用於加載靜態文本內容,之所以把靜態內容提取爲消息,是爲了能方便的集中管理頁面上某些可能會變動的內容。
    在resources目錄下新建messages.properties文件,加入配置:
home.data: i'm other data

html上的代碼:

<h1 th:text="#{home.data}">你好,這是一條消息</h1>
  • 條件判斷:if/unless
<p th:if="${user.userId} >= 1">用戶的id大於1,於1,所以能顯示這些</p>
<p th:unless="${user.userName == null }">當“用戶名稱爲空”這個條件不成立就顯示, 用戶名爲:<span th:text="${user.userName}">用戶名</span></p>
  • 分支條件判斷表達式:th:switch
<div th:switch="${user.userName}">
    <h1><p th:case="admin">他是管理員</p></h1>
    <h1><p th:case="admin2">這是第二個</p></h1>
    <h1><p th:case="*">你是遊客</p></h1>
</div>
  • 基本內置對象:
  1. ctx:上下文對象。
  2. vars: 上下文變量。
  3. locale:上下文語言環境。
  4. request:(只在Web上下文中)HttpServletRequest對象。
  5. response:(只在Web上下文中)HttpServletResponse對象。
  6. session:(只在Web上下文中)HttpSession對象。
  7. servletContext:(只在Web上下文中)ServletContext對象。
你的操作系統語言環境爲:
<span th:text="${#locale.language}"></span>,<span th:text="${#locale.displayCountry}"></span>,<span th:text="${#ctx.locale}"></span>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章