很好的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的各种表达式得到预期的动态数据,呈现在模板页面上。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章