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文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>net.hw</groupId>
- <artifactId>boot_thymeleaf_demo</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>boot_thymeleaf_demo</name>
- <description>Demo project for Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.3.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
2、在templates目錄創建index.html
默認的thymeleaf模板頁面應該放在resources/templates目錄裏。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8"/>
- <title>index</title>
- </head>
- <body>
- <h1>Thymeleaf Page: Welcome to Spring Boot World!</h1>
- <h1>File Location: resources/templates/index.html</h1>
- </body>
- </html>
3、創建控制器HomeController,定義請求映射方法
4、啓動程序,訪問http://localhost:8080/index
5、在main裏創建目錄結構webapp/WEB-INF/page,在裏面創建index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8"/>
- <title>index</title>
- </head>
- <body>
- <h1>Thymeleaf Page: Welcome to Spring Boot World!</h1>
- <h1>File Location: webapp/WEB-INF/page/index.html</h1>
- </body>
- </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='@{...}')
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <title>顯示學生信息</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-4">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">學生信息</span>
- </div>
- <div class="panel-body">
- 編號:<span th:text="#{student.id}">2</span><br/>
- 姓名:<span th:text="#{student.name}">萌萌噠</span><br/>
- 性別:<span th:text="#{student.gender}">男</span><br/>
- 年齡:<span th:text="#{student.age}">20</span><br/>
- 電話:<span th:text="#{student.telephone}">15890905678</span><br/>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
在客戶端顯示頁面:
只是顯示靜態數據,必須要通過服務端才能獲取動態數據,替換靜態數據,顯示在模板頁面。
4、在HomeController裏添加請求映射方法
此時,啓動程序,訪問http://localhost:8080/showStudent
沒有正確讀取application.properties文件裏定義的學生信息。
5、創建國際化配置類I18NConfig,定義資源包消息源Bean
- package net.hw.config;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.support.ResourceBundleMessageSource;
- import java.io.File;
- /**
- * Created by howard on 2017/4/25.
- */
- @Configuration
- public class I18NConfig {
- @Bean
- public ResourceBundleMessageSource messageSource() {
- ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
- messageSource.setUseCodeAsDefaultMessage(true);
- messageSource.setFallbackToSystemLocale(false);
- messageSource.setBasename("application");
- messageSource.setDefaultEncoding("UTF-8");
- messageSource.setCacheSeconds(2);
- return messageSource;
- }
- }
說明:
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
- student.id=1
- student.name=郭文玲
- student.gender=女
- student.age=18
- student.telephone=15890904568
學生信息的中文版,到時會根據系統語言環境讀取響應版本的屬性文件。
此時啓動程序,訪問http://localhost:8080/showStudent
大家可以看到,顯示的學生信息中文版,說明讀取的是application_zh_CN.properties屬性文件裏的數據。
6、創建用戶實體類User
- package net.hw.bean;
- import java.util.Date;
- /**
- * Created by howard on 2017/4/23.
- */
- public class User {
- /**
- * 用戶標識符
- */
- private int id;
- /**
- * 用戶名
- */
- private String username;
- /**
- * 密碼
- */
- private String password;
- /**
- * 電話號碼
- */
- private String telephone;
- /**
- * 註冊時間
- */
- private Date registerTime;
- /**
- * 權限(0:管理員;1:普通用戶)
- */
- private int popedom;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getTelephone() {
- return telephone;
- }
- public void setTelephone(String telephone) {
- this.telephone = telephone;
- }
- public Date getRegisterTime() {
- return registerTime;
- }
- public void setRegisterTime(Date registerTime) {
- this.registerTime = registerTime;
- }
- public int getPopedom() {
- return popedom;
- }
- public void setPopedom(int popedom) {
- this.popedom = popedom;
- }
- @Override
- public String toString() {
- return "User{" +
- "id=" + id +
- ", username='" + username + '\'' +
- ", password='" + password + '\'' +
- ", telephone='" + telephone + '\'' +
- ", registerTime=" + registerTime +
- ", popedom=" + popedom +
- '}';
- }
- }
7、創建UserService類
- package net.hw.service;
- import net.hw.bean.User;
- import org.springframework.stereotype.Service;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- /**
- * Created by howard on 2017/4/25.
- */
- @Service
- public class UserService {
- public User findOneUser() {
- User user = new User();
- user.setId(1);
- user.setUsername("李文強");
- user.setPassword("12345");
- user.setTelephone("15890904567");
- user.setRegisterTime(new Date());
- user.setPopedom(0);
- return user;
- }
- public List<User> findAllUsers() {
- List<User> users = new ArrayList<User>();
- User user = new User();
- user.setId(1);
- user.setUsername("李文強");
- user.setPassword("12345");
- user.setTelephone("15890904567");
- user.setRegisterTime(new Date());
- user.setPopedom(0);
- users.add(user);
- user = new User();
- user.setId(2);
- user.setUsername("張海洋");
- user.setPassword("11111");
- user.setTelephone("13990904567");
- user.setRegisterTime(new Date());
- user.setPopedom(1);
- users.add(user);
- user = new User();
- user.setId(3);
- user.setUsername("吳文燕");
- user.setPassword("22222");
- user.setTelephone("15890978905");
- user.setRegisterTime(new Date());
- user.setPopedom(1);
- users.add(user);
- user = new User();
- user.setId(4);
- user.setUsername("鄭智化");
- user.setPassword("33333");
- user.setTelephone("15990956905");
- user.setRegisterTime(new Date());
- user.setPopedom(1);
- users.add(user);
- return users;
- }
- }
9、在templates裏創建showOneUser.html
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8"/>
- <title>顯示用戶信息</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">用戶信息</span>
- </div>
- <div class="panel-body">
- 編號:<span th:text="${user.id}"></span><br/>
- 用戶名:<span th:text="${user.username}"></span><br/>
- 密碼:<span th:text="${user.password}"></span><br/>
- 電話:<span th:text="${user.telephone}"></span><br/>
- 註冊時間:<span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>
- 權限:<span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span><br/>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">用戶信息</span>
- </div>
- <div class="panel-body">
- <div th:object="${user}">
- 編號:<span th:text="*{id}"></span><br/>
- 用戶名:<span th:text="*{username}"></span><br/>
- 密碼:<span th:text="*{password}"></span><br/>
- 電話:<span th:text="*{telephone}"></span><br/>
- 註冊時間:<span th:text="*{#dates.format(registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>
- 權限:<span th:text="*{popedom==0?'管理員':'普通用戶'}"></span><br/>
- </div>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
說明:此頁面採用變量表達式${...}、選擇變量表達式*{...}。
爲了格式化註冊時間,採用#dates對象的format方法。
爲了將權限的數字0和1轉換成“管理員”和“普通用戶”,採用了三元運算符 (邏輯表達式)?(表達式1):(表達式2)。
10、創建showAllUsers.html
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8"/>
- <title>顯示全部用戶</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">全部用戶信息</span>
- </div>
- <div class="panel-body">
- <ul class="list-group">
- <li class="list-group-item" th:each="user:${users}">
- 編號:<span th:text="${user.id}"></span><br/>
- 用戶名:<span th:text="${user.username}"></span><br/>
- 密碼:<span th:text="${user.password}"></span><br/>
- 電話:<span th:text="${user.telephone}"></span><br/>
- 註冊時間:<span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span><br/>
- 權限:<span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span><br/>
- </li>
- </ul>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- <div class="col-md-7">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">全部用戶信息</span>
- </div>
- <div class="panel-body">
- <table class="table-bordered" style="width: 100%">
- <tr style="height: 40px; background-color: #f7ecb5">
- <th class="text-center">編號</th>
- <th class="text-center">用戶名</th>
- <th class="text-center">密碼</th>
- <th class="text-center">電話</th>
- <th class="text-center">註冊時間</th>
- <th class="text-center">權限</th>
- </tr>
- <tr th:each="user:${users}" class="text-center" style="height: 40px">
- <td><span th:text="${user.id}"></span></td>
- <td><span th:text="${user.username}"></span></td>
- <td><span th:text="${user.password}"></span></td>
- <td><span th:text="${user.telephone}"></span></td>
- <td><span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span></td>
- <td><span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span></td>
- </tr>
- </table>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
說明:左邊面板裏是卡片格式顯示用戶信息,右邊面板是表格形式顯示用戶信息。
課堂練習:修改showAllUser.html代碼,實現如下顯示效果。
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8"/>
- <title>顯示全部用戶</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">全部用戶信息</span>
- </div>
- <div class="panel-body">
- <ul class="list-group">
- <li class="list-group-item" th:each="user:${users}">
- <table class="table-bordered" style="width: 100%">
- <tr>
- <th>編號</th>
- <td><span th:text="${user.id}"></span></td>
- </tr>
- <tr>
- <th>用戶名</th>
- <td><span th:text="${user.username}"></span></td>
- </tr>
- <tr>
- <th>密碼</th>
- <td><span th:text="${user.password}"></span></td>
- </tr>
- <tr>
- <th>電話</th>
- <td><span th:text="${user.telephone}"></span></td>
- </tr>
- <tr>
- <th>註冊時間</th>
- <td><span th:text="${#dates.format(user.registerTime, 'yyyy-MM-dd hh:mm:ss')}"></span></td>
- </tr>
- <tr>
- <th>權限</th>
- <td><span th:text="${user.popedom==0?'管理員':'普通用戶'}"></span></td>
- </tr>
- </table>
- </li>
- </ul>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
11、在application.properties裏添加屬性
12、創建welcome.html(訪問帶參數的消息)
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <title>歡迎</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">瀘州職業技術學院</span>
- </div>
- <div class="panel-body">
- <span th:text="#{lzy.welcome(${name})}"></span>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
12、在HomeController裏添加請求映射方法
13、創建testThymeleafObjects.html
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <title>測試thymeleaf對象</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-10">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">測試Thymeleaf對象</span>
- </div>
- <div class="panel-body">
- #ctx.#vars:<br/>
- <textarea th:text="${#ctx.#vars}" rows="10" cols="150"></textarea><br/>
- 喜歡看的書:<span th:text="${#vars.book}"></span><br/>
- 喜歡的城市:<span th:text="${#httpSession.getAttribute('city')}"></span><br/>
- 你的國家:<span th:text="${#locale.country}+'-'+${#locale.getDisplayCountry()}"></span><br/>
- 你的母語:<span th:text="${#locale.language}+'-'+${#locale.getDisplayLanguage()}"></span><br/>
- <hr/>
- 時間:<span th:text="${#dates.format(#dates.createNow())}"></span><br/>
- 收入:<span th:text="'¥'+${#numbers.formatDecimal(2345.5645345, 3, 2)}"></span><br/>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
14、在HomeController裏添加請求映射方法
啓動程序,訪問http://localhost:8080/test
15、在pom.xml文件添加yaml的依賴
- <dependency>
- <groupId>org.yaml</groupId>
- <artifactId>snakeyaml</artifactId>
- <version>1.18</version>
- </dependency>
16、在resources裏創建application.yaml
- server:
- port: 8080
- serverHost:
- inetAddressA:
- ip: 127.0.0.1
- length: 160
- port: 2000
- inetAddressB:
- ip: 192.168.0.15
- length: 180
- port: 2000
- inetAddressB:
- ip: 192.168.0.16
- length: 288
- port: 2000
- udp:
- server:
- host: 192.168.60.34
- port: 8001
17、創建ServerHostProperties類
- package net.hw.properties;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.stereotype.Component;
- /**
- * Created by howard on 2017/4/27.
- */
- @Component
- @ConfigurationProperties("serverHost")
- public class ServerHostProperties {
- private InetAddress inetAddressA;
- private InetAddress inetAddressB;
- private InetAddress inetAddressC;
- public static class InetAddress {
- private String ip;
- private int length;
- private int port;
- public String getIp() {
- return ip;
- }
- public void setIp(String ip) {
- this.ip = ip;
- }
- public int getLength() {
- return length;
- }
- public void setLength(int length) {
- this.length = length;
- }
- public int getPort() {
- return port;
- }
- public void setPort(int port) {
- this.port = port;
- }
- }
- public InetAddress getInetAddressA() {
- return inetAddressA;
- }
- public void setInetAddressA(InetAddress inetAddressA) {
- this.inetAddressA = inetAddressA;
- }
- public InetAddress getInetAddressB() {
- return inetAddressB;
- }
- public void setInetAddressB(InetAddress inetAddressB) {
- this.inetAddressB = inetAddressB;
- }
- public InetAddress getInetAddressC() {
- return inetAddressC;
- }
- public void setInetAddressC(InetAddress inetAddressC) {
- this.inetAddressC = inetAddressC;
- }
- }
18、在webmvc子包裏創建ServerHostController
- package net.hw.webmvc;
- import net.hw.properties.ServerHostProperties;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by howard on 2017/4/27.
- */
- @Controller
- public class ServerHostController {
- @Autowired
- private ServerHostProperties serverHostProperties;
- @RequestMapping("/showServerHost")
- public String serverHost(Model model) {
- List<ServerHostProperties.InetAddress> inetAddresses = new ArrayList<ServerHostProperties.InetAddress>();
- inetAddresses.add(serverHostProperties.getInetAddressA());
- inetAddresses.add(serverHostProperties.getInetAddressB());
- inetAddresses.add(serverHostProperties.getInetAddressC());
- model.addAttribute("inetAddresses", inetAddresses);
- return "showServerHost";
- }
- }
19、在templates裏創建showServerHost.html
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org">
- <head>
- <title>顯示服務器主機信息</title>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <link th:href="@{/bootstrap/css/bootstrap.css}" href="../static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
- <link th:href="@{/bootstrap/css/bootstrap-theme.css}" href="../static/bootstrap/css/bootstrap-theme.css"
- rel="stylesheet"/>
- <script th:src="@{/scripts/jquery-3.1.1.min.js}" src="../static/scripts/jquery-3.1.1.min.js"></script>
- <script th:src="@{/bootstrap/js/bootstrap.js}" src="../static/bootstrap/js/bootstrap.js"></script>
- </head>
- <body>
- <div class="container">
- <div class="row">
- <div class="col-md-5">
- <div class="panel panel-primary">
- <div class="panel-heading text-center">
- <span class="panel-title">服務器主機信息</span>
- </div>
- <div class="panel-body">
- <ul class="list-group">
- <li class="list-group-item" th:each="inetAddress:${inetAddresses}">
- <div th:if="${inetAddressStat.count==1}">
- <p style="font-weight: bold">inetAddressA</p>
- </div>
- <div th:if="${inetAddressStat.count==2}">
- <p style="font-weight: bold">inetAddressB</p>
- </div>
- <div th:if="${inetAddressStat.count==3}">
- <p style="font-weight: bold">inetAddressC</p>
- </div>
- ip:<span th:text="${inetAddress.ip}"></span><br/>
- length:<span th:text="${inetAddress.length}"></span><br/>
- port:<span th:text="${inetAddress.port}"></span><br/>
- </li>
- </ul>
- </div>
- <div class="panel-footer text-right">
- <span class="panel-title">酒城工作室@2107</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
20、啓動程序,訪問http://localhost:8080/showServerHost
五、小結
採用Thymeleaf模板引擎,關鍵要注意動態數據與靜態數據,一個用於服務器端數據的獲取,一個用於客戶端數據的顯示,前端與後端很好地分離來處理,即使沒有啓動程序,也能在客戶端看到頁面的樣式效果。通過案例學會正確使用Thymeleaf的各種表達式得到預期的動態數據,呈現在模板頁面上。