很好的thymeleaf模板 入門例子

Thymealeaf模板引擎入門

一、Thymeleaf簡述

簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個極吸引人的特點:

1、Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。

2、Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。

3、Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。

二、Spring Boot項目Thymeleaf模板頁面存放位置
Spring Boot的Thymeleaf支持:

通過Thymeleaf類對集成所需的Bean進行自動配置,包括templateResolver、templateEngine和thymeleafViewResolver的配置。

1、創建Spring Boot項目boot_thymeleaf_demo

pom.xml文件:
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.    <modelVersion>4.0.0</modelVersion>  
  5.   
  6.    <groupId>net.hw</groupId>  
  7.    <artifactId>boot_thymeleaf_demo</artifactId>  
  8.    <version>0.0.1-SNAPSHOT</version>  
  9.    <packaging>jar</packaging>  
  10.   
  11.    <name>boot_thymeleaf_demo</name>  
  12.    <description>Demo project for Spring Boot</description>  
  13.   
  14.    <parent>  
  15.       <groupId>org.springframework.boot</groupId>  
  16.       <artifactId>spring-boot-starter-parent</artifactId>  
  17.       <version>1.5.3.RELEASE</version>  
  18.       <relativePath/> <!-- lookup parent from repository -->  
  19.    </parent>  
  20.   
  21.    <properties>  
  22.       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  23.       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  24.       <java.version>1.8</java.version>  
  25.    </properties>  
  26.   
  27.    <dependencies>  
  28.       <dependency>  
  29.          <groupId>org.springframework.boot</groupId>  
  30.          <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  31.       </dependency>  
  32.   
  33.       <dependency>  
  34.          <groupId>org.springframework.boot</groupId>  
  35.          <artifactId>spring-boot-starter-test</artifactId>  
  36.          <scope>test</scope>  
  37.       </dependency>  
  38.    </dependencies>  
  39.   
  40.    <build>  
  41.       <plugins>  
  42.          <plugin>  
  43.             <groupId>org.springframework.boot</groupId>  
  44.             <artifactId>spring-boot-maven-plugin</artifactId>  
  45.          </plugin>  
  46.       </plugins>  
  47.    </build>  
  48.   
  49. </project>  
2、在templates目錄創建index.html
默認的thymeleaf模板頁面應該放在resources/templates目錄裏。

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>index</title>  
  6. </head>  
  7. <body>  
  8. <h1>Thymeleaf Page: Welcome to Spring Boot World!</h1>  
  9. <h1>File Location: resources/templates/index.html</h1>  
  10. </body>  
  11. </html>  
3、創建控制器HomeController,定義請求映射方法

4、啓動程序,訪問http://localhost:8080/index

5、在main裏創建目錄結構webapp/WEB-INF/page,在裏面創建index.html

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>index</title>  
  6. </head>  
  7. <body>  
  8. <h1>Thymeleaf Page: Welcome to Spring Boot World!</h1>  
  9. <h1>File Location: webapp/WEB-INF/page/index.html</h1>  
  10. </body>  
  11. </html>  
6、在application.properties裏設置thymeleaf的前綴

7、啓動程序,訪問http://localhost:8080/index

由此可見,Spring Boot的自動配置確實很好用,只要設置一下屬性就可以輕易搞定。



引入bootstrap到上述項目:

三、Thymeleaf模板基本語法
(一)簡單表達式   
  1、變量的表達式:${...}
  2、選擇變量表達式:*{...}
  3、信息表達式:#{...}
  4、鏈接URL表達式:@{...}
(二)字面值
  1、文本文字:'one text', 'Another one!',…
  2、文字數量:0, 34, 3.0, 12.3,…
  3、布爾型常量:true, false
  4、空的文字:null
  5、文字標記:one, sometext, main,…
(四)文本處理
  1、字符串並置:+
  2、文字替換:|The name is ${name}|
(五)表達式基本對象
  1、#ctx:上下文對象
  2、#vars:上下文變量
  3、#locale:上下文語言環境
  4、#httpServletRequest:(只有在Web上下文)HttpServletRequest對象
  5、#httpSession:(只有在Web上下文)HttpSession對象。

用法:<span th:text="${#locale.country}">US</span>.

(六)實用工具對象 
#dates: java.util的實用方法。對象:日期格式、組件提取等.
#calendars:類似於#日期,但對於java.util。日曆對象
#numbers:格式化數字對象的實用方法。
#strings:字符串對象的實用方法:包含startsWith,將/附加等。
#objects:實用方法的對象。
#bools:布爾評價的實用方法。
#arrays:數組的實用方法。
#lists:list集合。
#sets:set集合。
#maps:map集合。
#aggregates:實用程序方法用於創建聚集在數組或集合.
#messages:實用程序方法獲取外部信息內部變量表達式,以同樣的方式,因爲它們將獲得使用# {…}語法
#ids:實用程序方法來處理可能重複的id屬性(例如,由於迭代)。

四、案例演示
1、在application.properties文件定義屬性

2、在templates裏創建showStudent.html
利用thymeleaf消息表達式#{...}訪問屬性文件的數據,主要用於國際化。
利用thymeleaf超鏈接表達式@{...}訪問靜態資源或動態資源。(th:src='@{...}'、th:href='@{...}'、th:action='@{...}')
[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <title>顯示學生信息</title>  
  5.     <meta charset="UTF-8"/>  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  7.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  9.           rel="stylesheet"/>  
  10.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  11.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  12. </head>  
  13. <body>  
  14. <div class="container">  
  15.     <div class="row">  
  16.         <div class="col-md-4">  
  17.             <div class="panel panel-primary">  
  18.                 <div class="panel-heading text-center">  
  19.                     <span class="panel-title">學生信息</span>  
  20.                 </div>  
  21.                 <div class="panel-body">  
  22.                     編號:<span th:text="#{student.id}">2</span><br/>  
  23.                     姓名:<span th:text="#{student.name}">萌萌噠</span><br/>  
  24.                     性別:<span th:text="#{student.gender}"></span><br/>  
  25.                     年齡:<span th:text="#{student.age}">20</span><br/>  
  26.                     電話:<span th:text="#{student.telephone}">15890905678</span><br/>  
  27.                 </div>  
  28.                 <div class="panel-footer text-right">  
  29.                     <span class="panel-title">酒城工作室@2107</span>  
  30.                 </div>  
  31.             </div>  
  32.         </div>  
  33.     </div>  
  34. </div>  
  35. </body>  
  36. </html>  
在客戶端顯示頁面:

只是顯示靜態數據,必須要通過服務端才能獲取動態數據,替換靜態數據,顯示在模板頁面。

4、在HomeController裏添加請求映射方法

此時,啓動程序,訪問http://localhost:8080/showStudent

沒有正確讀取application.properties文件裏定義的學生信息。

5、創建國際化配置類I18NConfig,定義資源包消息源Bean

[java] view plain copy
  1. package net.hw.config;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.Configuration;  
  5. import org.springframework.context.support.ResourceBundleMessageSource;  
  6.   
  7. import java.io.File;  
  8.   
  9. /** 
  10.  * Created by howard on 2017/4/25. 
  11.  */  
  12. @Configuration  
  13. public class I18NConfig {  
  14.     @Bean  
  15.     public ResourceBundleMessageSource messageSource() {  
  16.         ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();  
  17.         messageSource.setUseCodeAsDefaultMessage(true);  
  18.         messageSource.setFallbackToSystemLocale(false);  
  19.         messageSource.setBasename("application");  
  20.         messageSource.setDefaultEncoding("UTF-8");  
  21.         messageSource.setCacheSeconds(2);  
  22.         return messageSource;  
  23.     }  
  24. }  


說明:
setBaseName設置消息源的文件名,messageSource.setBasename("application");,表明消息源是以applicition打頭的屬性文件,如果要設置多個屬性文件作爲消息源,那麼就要用setBaseNames方法來設置,比如:messageSource.setBasenames("student", "application"); 這樣就有兩個消息源:student.properties和application.properties。

此時啓動程序,訪問http://localhost:8080/showStudent

替換了靜態數據,說明成功讀取了application.properties裏的數據。

5、在resources裏創建application_zh_CN.properties

[html] view plain copy
  1. student.id=1  
  2. student.name=郭文玲  
  3. student.gender=女  
  4. student.age=18  
  5. student.telephone=15890904568  
學生信息的中文版,到時會根據系統語言環境讀取響應版本的屬性文件。

此時啓動程序,訪問http://localhost:8080/showStudent

大家可以看到,顯示的學生信息中文版,說明讀取的是application_zh_CN.properties屬性文件裏的數據。


6、創建用戶實體類User

[java] view plain copy
  1. package net.hw.bean;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  * Created by howard on 2017/4/23. 
  7.  */  
  8. public class User {  
  9.     /** 
  10.      * 用戶標識符 
  11.      */  
  12.     private int id;  
  13.     /** 
  14.      * 用戶名 
  15.      */  
  16.     private String username;  
  17.     /** 
  18.      * 密碼 
  19.      */  
  20.     private String password;  
  21.     /** 
  22.      * 電話號碼 
  23.      */  
  24.     private String telephone;  
  25.     /** 
  26.      * 註冊時間 
  27.      */  
  28.     private Date registerTime;  
  29.     /** 
  30.      * 權限(0:管理員;1:普通用戶) 
  31.      */  
  32.     private int popedom;  
  33.   
  34.     public int getId() {  
  35.         return id;  
  36.     }  
  37.   
  38.     public void setId(int id) {  
  39.         this.id = id;  
  40.     }  
  41.   
  42.     public String getUsername() {  
  43.         return username;  
  44.     }  
  45.   
  46.     public void setUsername(String username) {  
  47.         this.username = username;  
  48.     }  
  49.   
  50.     public String getPassword() {  
  51.         return password;  
  52.     }  
  53.   
  54.     public void setPassword(String password) {  
  55.         this.password = password;  
  56.     }  
  57.   
  58.     public String getTelephone() {  
  59.         return telephone;  
  60.     }  
  61.   
  62.     public void setTelephone(String telephone) {  
  63.         this.telephone = telephone;  
  64.     }  
  65.   
  66.     public Date getRegisterTime() {  
  67.         return registerTime;  
  68.     }  
  69.   
  70.     public void setRegisterTime(Date registerTime) {  
  71.         this.registerTime = registerTime;  
  72.     }  
  73.   
  74.     public int getPopedom() {  
  75.         return popedom;  
  76.     }  
  77.   
  78.     public void setPopedom(int popedom) {  
  79.         this.popedom = popedom;  
  80.     }  
  81.   
  82.     @Override  
  83.     public String toString() {  
  84.         return "User{" +  
  85.                 "id=" + id +  
  86.                 ", username='" + username + '\'' +  
  87.                 ", password='" + password + '\'' +  
  88.                 ", telephone='" + telephone + '\'' +  
  89.                 ", registerTime=" + registerTime +  
  90.                 ", popedom=" + popedom +  
  91.                 '}';  
  92.     }  
  93. }  
7、創建UserService類

[java] view plain copy
  1. package net.hw.service;  
  2.   
  3. import net.hw.bean.User;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import java.util.ArrayList;  
  7. import java.util.Date;  
  8. import java.util.List;  
  9.   
  10. /** 
  11.  * Created by howard on 2017/4/25. 
  12.  */  
  13. @Service  
  14. public class UserService {  
  15.     public User findOneUser() {  
  16.         User user = new User();  
  17.         user.setId(1);  
  18.         user.setUsername("李文強");  
  19.         user.setPassword("12345");  
  20.         user.setTelephone("15890904567");  
  21.         user.setRegisterTime(new Date());  
  22.         user.setPopedom(0);  
  23.         return user;  
  24.     }  
  25.   
  26.     public List<User> findAllUsers() {  
  27.         List<User> users = new ArrayList<User>();  
  28.   
  29.         User user = new User();  
  30.         user.setId(1);  
  31.         user.setUsername("李文強");  
  32.         user.setPassword("12345");  
  33.         user.setTelephone("15890904567");  
  34.         user.setRegisterTime(new Date());  
  35.         user.setPopedom(0);  
  36.         users.add(user);  
  37.   
  38.         user = new User();  
  39.         user.setId(2);  
  40.         user.setUsername("張海洋");  
  41.         user.setPassword("11111");  
  42.         user.setTelephone("13990904567");  
  43.         user.setRegisterTime(new Date());  
  44.         user.setPopedom(1);  
  45.         users.add(user);  
  46.   
  47.         user = new User();  
  48.         user.setId(3);  
  49.         user.setUsername("吳文燕");  
  50.         user.setPassword("22222");  
  51.         user.setTelephone("15890978905");  
  52.         user.setRegisterTime(new Date());  
  53.         user.setPopedom(1);  
  54.         users.add(user);  
  55.   
  56.         user = new User();  
  57.         user.setId(4);  
  58.         user.setUsername("鄭智化");  
  59.         user.setPassword("33333");  
  60.         user.setTelephone("15990956905");  
  61.         user.setRegisterTime(new Date());  
  62.         user.setPopedom(1);  
  63.         users.add(user);  
  64.   
  65.         return users;  
  66.     }  
  67. }  
9、在templates裏創建showOneUser.html

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>顯示用戶信息</title>  
  6.     <meta charset="UTF-8"/>  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  9.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  10.           rel="stylesheet"/>  
  11.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  12.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  13. </head>  
  14. <body>  
  15. <div class="container">  
  16.     <div class="row">  
  17.         <div class="col-md-5">  
  18.             <div class="panel panel-primary">  
  19.                 <div class="panel-heading text-center">  
  20.                     <span class="panel-title">用戶信息</span>  
  21.                 </div>  
  22.                 <div class="panel-body">  
  23.                     編號:<span th:text="${user.id}"></span><br/>  
  24.                     用戶名:<span th:text="${user.username}"></span><br/>  
  25.                     密碼:<span th:text="${user.password}"></span><br/>  
  26.                     電話:<span th:text="${user.telephone}"></span><br/>  
  27.                     註冊時間:<span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>  
  28.                     權限:<span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span><br/>  
  29.                 </div>  
  30.                 <div class="panel-footer text-right">  
  31.                     <span class="panel-title">酒城工作室@2107</span>  
  32.                 </div>  
  33.             </div>  
  34.         </div>  
  35.     </div>  
  36.     <div class="row">  
  37.         <div class="col-md-5">  
  38.             <div class="panel panel-primary">  
  39.                 <div class="panel-heading text-center">  
  40.                     <span class="panel-title">用戶信息</span>  
  41.                 </div>  
  42.                 <div class="panel-body">  
  43.                     <div th:object="${user}">  
  44.                         編號:<span th:text="*{id}"></span><br/>  
  45.                         用戶名:<span th:text="*{username}"></span><br/>  
  46.                         密碼:<span th:text="*{password}"></span><br/>  
  47.                         電話:<span th:text="*{telephone}"></span><br/>  
  48.                         註冊時間:<span th:text="*{#dates.format(registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>  
  49.                         權限:<span th:text="*{popedom==0?'管理員':'普通用戶'}"></span><br/>  
  50.                     </div>  
  51.                 </div>  
  52.                 <div class="panel-footer text-right">  
  53.                     <span class="panel-title">酒城工作室@2107</span>  
  54.                 </div>  
  55.             </div>  
  56.         </div>  
  57.     </div>  
  58. </div>  
  59. </body>  
  60. </html>  
說明:此頁面採用變量表達式${...}、選擇變量表達式*{...}。
爲了格式化註冊時間,採用#dates對象的format方法。
爲了將權限的數字0和1轉換成“管理員”和“普通用戶”,採用了三元運算符 (邏輯表達式)?(表達式1):(表達式2)。

10、創建showAllUsers.html

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>顯示全部用戶</title>  
  6.     <meta charset="UTF-8"/>  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  9.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  10.           rel="stylesheet"/>  
  11.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  12.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  13. </head>  
  14. <body>  
  15. <div class="container">  
  16.     <div class="row">  
  17.         <div class="col-md-5">  
  18.             <div class="panel panel-primary">  
  19.                 <div class="panel-heading text-center">  
  20.                     <span class="panel-title">全部用戶信息</span>  
  21.                 </div>  
  22.                 <div class="panel-body">  
  23.                     <ul class="list-group">  
  24.                         <li class="list-group-item" th:each="user:${users}">  
  25.                             編號:<span th:text="${user.id}"></span><br/>  
  26.                             用戶名:<span th:text="${user.username}"></span><br/>  
  27.                             密碼:<span th:text="${user.password}"></span><br/>  
  28.                             電話:<span th:text="${user.telephone}"></span><br/>  
  29.                             註冊時間:<span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>  
  30.                             權限:<span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span><br/>  
  31.                         </li>  
  32.                     </ul>  
  33.                 </div>  
  34.                 <div class="panel-footer text-right">  
  35.                     <span class="panel-title">酒城工作室@2107</span>  
  36.                 </div>  
  37.             </div>  
  38.         </div>  
  39.         <div class="col-md-7">  
  40.             <div class="panel panel-primary">  
  41.                 <div class="panel-heading text-center">  
  42.                     <span class="panel-title">全部用戶信息</span>  
  43.                 </div>  
  44.                 <div class="panel-body">  
  45.                     <table class="table-bordered" style="width: 100%">  
  46.                         <tr style="height: 40px; background-color: #f7ecb5">  
  47.                             <th class="text-center">編號</th>  
  48.                             <th class="text-center">用戶名</th>  
  49.                             <th class="text-center">密碼</th>  
  50.                             <th class="text-center">電話</th>  
  51.                             <th class="text-center">註冊時間</th>  
  52.                             <th class="text-center">權限</th>  
  53.                         </tr>  
  54.                         <tr th:each="user:${users}" class="text-center" style="height: 40px">  
  55.                             <td><span th:text="${user.id}"></span></td>  
  56.                             <td><span th:text="${user.username}"></span></td>  
  57.                             <td><span th:text="${user.password}"></span></td>  
  58.                             <td><span th:text="${user.telephone}"></span></td>  
  59.                             <td><span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span></td>  
  60.                             <td><span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span></td>  
  61.                         </tr>  
  62.                     </table>  
  63.                 </div>  
  64.                 <div class="panel-footer text-right">  
  65.                     <span class="panel-title">酒城工作室@2107</span>  
  66.                 </div>  
  67.             </div>  
  68.         </div>  
  69.     </div>  
  70. </div>  
  71. </body>  
  72. </html>  

說明:左邊面板裏是卡片格式顯示用戶信息,右邊面板是表格形式顯示用戶信息。

課堂練習:修改showAllUser.html代碼,實現如下顯示效果。

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <meta charset="UTF-8"/>  
  5.     <title>顯示全部用戶</title>  
  6.     <meta charset="UTF-8"/>  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  9.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  10.           rel="stylesheet"/>  
  11.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  12.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  13. </head>  
  14. <body>  
  15. <div class="container">  
  16.     <div class="row">  
  17.         <div class="col-md-5">  
  18.             <div class="panel panel-primary">  
  19.                 <div class="panel-heading text-center">  
  20.                     <span class="panel-title">全部用戶信息</span>  
  21.                 </div>  
  22.                 <div class="panel-body">  
  23.                     <ul class="list-group">  
  24.                         <li class="list-group-item" th:each="user:${users}">  
  25.                             <table class="table-bordered" style="width: 100%">  
  26.                                 <tr>  
  27.                                     <th>編號</th>  
  28.                                     <td><span th:text="${user.id}"></span></td>  
  29.                                 </tr>  
  30.                                 <tr>  
  31.                                     <th>用戶名</th>  
  32.                                     <td><span th:text="${user.username}"></span></td>  
  33.                                 </tr>  
  34.                                 <tr>  
  35.                                     <th>密碼</th>  
  36.                                     <td><span th:text="${user.password}"></span></td>  
  37.                                 </tr>  
  38.                                 <tr>  
  39.                                     <th>電話</th>  
  40.                                     <td><span th:text="${user.telephone}"></span></td>  
  41.                                 </tr>  
  42.                                 <tr>  
  43.                                     <th>註冊時間</th>  
  44.                                     <td><span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span></td>  
  45.                                 </tr>  
  46.                                 <tr>  
  47.                                     <th>權限</th>  
  48.                                     <td><span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span></td>  
  49.                                 </tr>  
  50.                             </table>  
  51.                         </li>  
  52.                     </ul>  
  53.                 </div>  
  54.                 <div class="panel-footer text-right">  
  55.                     <span class="panel-title">酒城工作室@2107</span>  
  56.                 </div>  
  57.             </div>  
  58.         </div>  
  59.     </div>  
  60. </div>  
  61. </body>  
  62. </html>  
11、在application.properties裏添加屬性

12、創建welcome.html(訪問帶參數的消息)

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <title>歡迎</title>  
  5.     <meta charset="UTF-8"/>  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  7.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  9.           rel="stylesheet"/>  
  10.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  11.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  12. </head>  
  13. <body>  
  14. <div class="container">  
  15.     <div class="row">  
  16.         <div class="col-md-5">  
  17.             <div class="panel panel-primary">  
  18.                 <div class="panel-heading text-center">  
  19.                     <span class="panel-title">瀘州職業技術學院</span>  
  20.                 </div>  
  21.                 <div class="panel-body">  
  22.                     <span th:text="#{lzy.welcome(${name})}"></span>  
  23.                 </div>  
  24.                 <div class="panel-footer text-right">  
  25.                     <span class="panel-title">酒城工作室@2107</span>  
  26.                 </div>  
  27.             </div>  
  28.         </div>  
  29.     </div>  
  30. </div>  
  31. </body>  
  32. </html>  
12、在HomeController裏添加請求映射方法

啓動程序,訪問http://localhost:8080/welcome

13、創建testThymeleafObjects.html

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <title>測試thymeleaf對象</title>  
  5.     <meta charset="UTF-8"/>  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  7.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  9.           rel="stylesheet"/>  
  10.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  11.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  12. </head>  
  13. <body>  
  14. <div class="container">  
  15.     <div class="row">  
  16.         <div class="col-md-10">  
  17.             <div class="panel panel-primary">  
  18.                 <div class="panel-heading text-center">  
  19.                     <span class="panel-title">測試Thymeleaf對象</span>  
  20.                 </div>  
  21.                 <div class="panel-body">  
  22.                     #ctx.#vars:<br/>  
  23.                     <textarea th:text="${#ctx.#vars}" rows="10" cols="150"></textarea><br/>  
  24.                     喜歡看的書:<span th:text="${#vars.book}"></span><br/>  
  25.                     喜歡的城市:<span th:text="${#httpSession.getAttribute('city')}"></span><br/>  
  26.                     你的國家:<span th:text="${#locale.country}+'-'+${#locale.getDisplayCountry()}"></span><br/>  
  27.                     你的母語:<span th:text="${#locale.language}+'-'+${#locale.getDisplayLanguage()}"></span><br/>  
  28.                     <hr/>  
  29.                     時間:<span th:text="${#dates.format(#dates.createNow())}"></span><br/>  
  30.                     收入:<span th:text="'¥'+${#numbers.formatDecimal(2345.5645345, 3, 2)}"></span><br/>  
  31.                 </div>  
  32.                 <div class="panel-footer text-right">  
  33.                     <span class="panel-title">酒城工作室@2107</span>  
  34.                 </div>  
  35.             </div>  
  36.         </div>  
  37.     </div>  
  38. </div>  
  39. </body>  
  40. </html>  
14、在HomeController裏添加請求映射方法

啓動程序,訪問http://localhost:8080/test

15、在pom.xml文件添加yaml的依賴
[html] view plain copy
  1. <dependency>  
  2.    <groupId>org.yaml</groupId>  
  3.    <artifactId>snakeyaml</artifactId>  
  4.    <version>1.18</version>  
  5. </dependency>  
16、在resources裏創建application.yaml

[html] view plain copy
  1. server:  
  2.   port: 8080  
  3.   
  4. serverHost:  
  5.   inetAddressA:  
  6.     ip: 127.0.0.1  
  7.     length: 160  
  8.     port: 2000      
  9.   inetAddressB:  
  10.     ip: 192.168.0.15  
  11.     length: 180  
  12.     port: 2000    
  13.   inetAddressB:  
  14.       ip: 192.168.0.16  
  15.       length: 288  
  16.       port: 2000  
  17.         
  18. udp:  
  19.   server:  
  20.     host: 192.168.60.34  
  21.     port: 8001  
17、創建ServerHostProperties類

[java] view plain copy
  1. package net.hw.properties;  
  2.   
  3. import org.springframework.boot.context.properties.ConfigurationProperties;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. /** 
  7.  * Created by howard on 2017/4/27. 
  8.  */  
  9. @Component  
  10. @ConfigurationProperties("serverHost")  
  11. public class ServerHostProperties {  
  12.     private InetAddress inetAddressA;  
  13.     private InetAddress inetAddressB;  
  14.     private InetAddress inetAddressC;  
  15.   
  16.     public static class InetAddress {  
  17.         private String ip;  
  18.         private int length;  
  19.         private int port;  
  20.   
  21.         public String getIp() {  
  22.             return ip;  
  23.         }  
  24.   
  25.         public void setIp(String ip) {  
  26.             this.ip = ip;  
  27.         }  
  28.   
  29.         public int getLength() {  
  30.             return length;  
  31.         }  
  32.   
  33.         public void setLength(int length) {  
  34.             this.length = length;  
  35.         }  
  36.   
  37.         public int getPort() {  
  38.             return port;  
  39.         }  
  40.   
  41.         public void setPort(int port) {  
  42.             this.port = port;  
  43.         }  
  44.     }  
  45.   
  46.     public InetAddress getInetAddressA() {  
  47.         return inetAddressA;  
  48.     }  
  49.   
  50.     public void setInetAddressA(InetAddress inetAddressA) {  
  51.         this.inetAddressA = inetAddressA;  
  52.     }  
  53.   
  54.     public InetAddress getInetAddressB() {  
  55.         return inetAddressB;  
  56.     }  
  57.   
  58.     public void setInetAddressB(InetAddress inetAddressB) {  
  59.         this.inetAddressB = inetAddressB;  
  60.     }  
  61.   
  62.     public InetAddress getInetAddressC() {  
  63.         return inetAddressC;  
  64.     }  
  65.   
  66.     public void setInetAddressC(InetAddress inetAddressC) {  
  67.         this.inetAddressC = inetAddressC;  
  68.     }  
  69. }  
18、在webmvc子包裏創建ServerHostController

[java] view plain copy
  1. package net.hw.webmvc;  
  2.   
  3. import net.hw.properties.ServerHostProperties;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.ui.Model;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8.   
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. /** 
  13.  * Created by howard on 2017/4/27. 
  14.  */  
  15. @Controller  
  16. public class ServerHostController {  
  17.     @Autowired  
  18.     private ServerHostProperties serverHostProperties;  
  19.   
  20.     @RequestMapping("/showServerHost")  
  21.     public String serverHost(Model model) {  
  22.         List<ServerHostProperties.InetAddress> inetAddresses = new ArrayList<ServerHostProperties.InetAddress>();  
  23.         inetAddresses.add(serverHostProperties.getInetAddressA());  
  24.         inetAddresses.add(serverHostProperties.getInetAddressB());  
  25.         inetAddresses.add(serverHostProperties.getInetAddressC());  
  26.         model.addAttribute("inetAddresses", inetAddresses);  
  27.         return "showServerHost";  
  28.     }  
  29. }  
19、在templates裏創建showServerHost.html

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html xmlns:th="http://www.thymeleaf.org">  
  3. <head>  
  4.     <title>顯示服務器主機信息</title>  
  5.     <meta charset="UTF-8"/>  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1"/>  
  7.     <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>  
  8.     <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"  
  9.           rel="stylesheet"/>  
  10.     <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>  
  11.     <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>  
  12. </head>  
  13. <body>  
  14. <div class="container">  
  15.     <div class="row">  
  16.         <div class="col-md-5">  
  17.             <div class="panel panel-primary">  
  18.                 <div class="panel-heading text-center">  
  19.                     <span class="panel-title">服務器主機信息</span>  
  20.                 </div>  
  21.                 <div class="panel-body">  
  22.                     <ul class="list-group">  
  23.                         <li class="list-group-item" th:each="inetAddress:${inetAddresses}">  
  24.                             <div th:if="${inetAddressStat.count==1}">  
  25.                                 <p style="font-weight: bold">inetAddressA</p>  
  26.                             </div>  
  27.                             <div th:if="${inetAddressStat.count==2}">  
  28.                                 <p style="font-weight: bold">inetAddressB</p>  
  29.                             </div>  
  30.                             <div th:if="${inetAddressStat.count==3}">  
  31.                                 <p style="font-weight: bold">inetAddressC</p>  
  32.                             </div>  
  33.                             ip:<span th:text="${inetAddress.ip}"></span><br/>  
  34.                             length:<span th:text="${inetAddress.length}"></span><br/>  
  35.                             port:<span th:text="${inetAddress.port}"></span><br/>  
  36.                         </li>  
  37.                     </ul>  
  38.                 </div>  
  39.                 <div class="panel-footer text-right">  
  40.                     <span class="panel-title">酒城工作室@2107</span>  
  41.                 </div>  
  42.             </div>  
  43.         </div>  
  44.     </div>  
  45. </div>  
  46. </body>  
  47. </html>  
20、啓動程序,訪問http://localhost:8080/showServerHost

五、小結
採用Thymeleaf模板引擎,關鍵要注意動態數據與靜態數據,一個用於服務器端數據的獲取,一個用於客戶端數據的顯示,前端與後端很好地分離來處理,即使沒有啓動程序,也能在客戶端看到頁面的樣式效果。通過案例學會正確使用Thymeleaf的各種表達式得到預期的動態數據,呈現在模板頁面上。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章