zoukankan      html  css  js  c++  java
  • Thymeleaf-模板引擎

    一,Thymeleaf 简介

    Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

    1,Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

    2,Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

    3.,Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

    二,Hello Thymeleaf实例

    1,创建Maven项目

    具体步骤参照:Eclipse中创建Maven Web项目

    2,添加Spring的依赖

    具体步骤参考:Maven创建Spring MVC项目

    3,修改pom.xml文件,加入Thymeleaf

    <!-- thymeleaf模板引擎 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>

    4,在Spring MVC配置文件中添加thymeleaf视图解释器

    <!-- 视图解析器 -->
    <!-- 使用thymeleaf解析  -->
    <bean id="templateResolver"
        class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
        <!-- 缓存-->
        <property name="cacheable" value="false"/>
    </bean>
    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>
     
    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <!--解决中文乱码-->  
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    关闭Thymeleaf页面的缓存,可以让对页面的改动及时反映到视图中。

    5,创建一个页面

    html页面标签中引入如下:

    <html xmlns:th="http://www.thymeleaf.org">

    具体html页面如下:

    <!DOCTYPE html>
    <html lang="zh-CN"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8"/>
    <title>index</title>
    </head>
    <body>
        Hello Thymeleaf!
    </body>
    </html>

    6,创建一个Controller

    @Controller
    @RequestMapping("/index")
    public class IndexController {
        
        @RequestMapping("returnString")
        public String returnString(){
            return "index";
        }
    }

    7,运行项目访问IndexController

    三,页面参数获取/回显

    1,创建一个pojo

    public class Person {
        private int id;
        private String name;
        private String addrs;
        public Person(int id, String name, String addrs) {
            super();
            this.id = id;
            this.name = name;
            this.addrs = addrs;
        }
        public Person() {
            super();
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAddrs() {
            return addrs;
        }
        public void setAddrs(String addrs) {
            this.addrs = addrs;
        }
        @Override
        public String toString() {
            return "Person [id=" + id + ", name=" + name + ", addrs=" + addrs + "]";
        }
    }

    2,创建提交表单页面person.html

    <!DOCTYPE html>
    <html lang="zh-CN"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8"/>
    <title>person</title>
    <link href="css/bootstrap.css" rel="stylesheet"/>
    <script src="js/jquery-3.2.1.js"></script>
    <script src="js/bootstrap.js"></script>
    </head>
    <body>
        <form th:action="@{savePerson}" th:method="post">
            <div class="form-group">
                <label class="col-sm-2 control-label">id</label> 
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="id" placeholder="id" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="name" placeholder="name" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">地址</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="addrs" placeholder="addrs" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">提交</button>
                </div>
            </div>
        </form>
    </body>
    </html>

    解释:

    th:action属性

    表示其值代替静态页面的action的值。等价action='/savePerson'。

    th:method属性

    表示其值将代替静态页面的method的值。等价method='post'。

    3,创建回显页面return.html

    <!DOCTYPE html>
    <html lang="zh-CN"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8"/>
    <title>return</title>
    <link href="css/bootstrap.css" rel="stylesheet"/>
    <script src="js/jquery-3.2.1.js"></script>
    <script src="js/bootstrap.js"></script>
    </head>
    <body>
        <!-- from表单获取提交过来的数据 -->
        <h3>from表单获取提交过来的数据</h3>
        <form th:action="@{savePerson}" th:method="post" th:object="${person}">
            <div class="form-group">
                <label class="col-sm-2 control-label">id</label> 
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="id" placeholder="id" th:value="*{id}"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="name" placeholder="name" th:value="*{name}"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">地址</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="addrs" placeholder="addrs" th:value="*{addrs}"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">提交</button>
                </div>
            </div>
        </form>
        <!-- 表格获取提交过来的数据 -->
        <h3>表格获取提交过来的数据 </h3>
        <table class="table" th:object="${person}">
          <tr>
            <td>id</td>
            <td>name</td>
            <td>addrs</td>
          </tr>
          <tr>
            <td th:text="${person.id}"></td>
            <td th:text="${person.name}"></td>
            <td th:text="${person.addrs}"></td>
          </tr>
        </table>
    </body>
    </html>

    解释:

    th:object属性

    表示有一个属性名为"person"的Java bean传递到页面上来。可以通过表达式*{fieldName}才能取得其值。

    th:value属性

    表示取得Person实例中的属性值,也就是通过调用Java bean的get方法获得。等价于标签value='xxx'

    th:text属性

    文本显示。等价于标签text='xxx'

    4,创建PersonController

    @Controller
    public class PersonController {
        @RequestMapping
        public String returnString(){
            return "person";
        }
        
        @RequestMapping("/savePerson")
        public String savePerson(Model Model ,Person person){
            Model.addAttribute("person", person);
            return "return";
        }
    }

    运行访问:http://localhost:8081/Thymeleaf/,点击提交

    运行结果:

    四,基本表达式

    1,${}

    变量表达式(美元表达式),用于访问容器上下文环境中的数据,功能与jstl中${}的相同。

    <td th:text="${person.id}"></td>
    <td th:text="${person.name}"></td>
    <td th:text="${person.addrs}"></td>

    2,*{}

    选择表达式(星号表达式),获取选定对象里的数据域(th:object属性用于绑定对象)。

    选择表达式与变量表达式的区别:

    选择表达式计算的是选定的对象,而不是整个环境变量映射。也就是:只要是没有选择的对象,选择表达式与变量表达式的语法是完全一样的。

    <!-- from表单获取提交过来的数据 -->
    <h3>from表单获取提交过来的数据</h3>
    <form th:action="@{savePerson}" th:method="post" th:object="${person}">
        <div class="form-group">
            <label class="col-sm-2 control-label">id</label> 
            <div class="col-sm-10">
                <input type="text" class="form-control" name="id" placeholder="id" th:value="*{id}"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">名称</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="name" placeholder="name" th:value="*{name}"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">地址</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="addrs" placeholder="addrs" th:value="*{addrs}"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>

    3,#{}

    没明白怎么使用!自己测试不出来。希望看见的大佬能指点迷津。

    4,@{}

    超链接url表达式。

    <script th:src="@{/js/jquery/jquery.js}"></script>

    五,常用属性

    1,th:action

    定义后台控制器路径,类似<form>标签的action属性。
    2,th:each

    对象遍历,功能类似jstl中的<c:forEach>标签

    Controller

    @RequestMapping("/listPerson")
    public String listPerson(Model Model){
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(1, "Zender", "Shanghai"));
        list.add(new Person(2, "Zender2", "Shanghai2"));
        list.add(new Person(3, "Zender3", "Shanghai3"));
        Model.addAttribute("listPerson", list);
        return "listPerson";
    }

    页面

    <head>
    <meta charset="UTF-8"/>
    <title>listPerson</title>
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet"/>
    <script th:src="@{/js/jquery-3.2.1.js}"></script>
    <script th:src="@{/js/bootstrap.js}"></script>
    </head>
    <body>
        <h3>each循环</h3>
        <table class="table">
          <tr>
            <td>id</td>
            <td>name</td>
            <td>addrs</td>
          </tr>
          <tbody th:each="person,personStat:${listPerson}">
              <tr>
                <td th:text="${person.id}"></td>
                <td th:text="${person.name}"></td>
                <td th:text="${person.addrs}"></td>
              </tr>
          </tbody>
        </table>
    </body>
    </html>

    personStat称作状态变量,属性有:

    index

    当前迭代对象的index(从0开始计算)。

    count

    当前迭代对象的index(从1开始计算)。

    size

    被迭代对象的大小。

    current

    当前迭代变量。

    even/odd

    布尔值,当前循环是否是偶数/奇数(从0开始计算)。

    first

    布尔值,当前循环是否是第一个。

    last

    布尔值,当前循环是否是最后一个。

    3,th:field

    常用于表单字段绑定。通常与th:object一起使用。 属性绑定、集合绑定。

    Controller

    @RequestMapping("/person")
    public String returnString(){
        return "person";
    }
     
    @RequestMapping("/savePerson")
    public String savePerson(Model Model ,Person person){
        Model.addAttribute("person", person);
        return "return";
    }

    表单页面

    <form th:action="@{savePerson}" th:method="post">
        <div class="form-group">
            <label class="col-sm-2 control-label">id</label> 
            <div class="col-sm-10">
                <input type="text" class="form-control" name="id" placeholder="id" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">名称</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="name" placeholder="name" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">地址</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="addrs" placeholder="addrs" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>

    回显页面

    <!-- from表单获取提交过来的数据 -->
    <h3>from表单获取提交过来的数据</h3>
    <form th:action="@{savePerson}" th:method="post" th:object="${person}">
        <div class="form-group">
            <label class="col-sm-2 control-label">id</label> 
            <div class="col-sm-10">
                <input type="text" class="form-control" name="id" placeholder="id" th:field="*{id}"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">名称</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="name" placeholder="name" th:field="*{name}"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">地址</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="addrs" placeholder="addrs" th:field="*{addrs}"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>

    4,th:href

    定义超链接。

    <link th:href="@{/css/bootstrap.css}" rel="stylesheet"/>

    5,th:id

    id声明,类似html标签中的id属性。

    <div th:id="ids"></div>

    6th:if,th:unless

    th:if条件判断,th:if中条件成立时才显示。

    th:unless于th:if恰好相反,表达式中的条件不成立,才会显示其内容。

    <div th:if="${person.id} == 0">123</div>

    7,th:include,th:replace和th:fragment

    th:fragment

    布局标签,定义一个代码片段,方便其它地方引用。常与th:include,th:replace一起使用。

    th:include

    布局标签,替换内容到引入的文件。

    th:replace

    布局标签,替换整个标签到引入的文件。

    模板文件footer.html:

    <div th:fragment="footer" >
        Copyright ©2018 Zender
    </div>
    <div th:fragment="head" >
        头部 Zender
    </div>

    页面index.html

    <body>
        <div th:include="../templates/footer :: head"></div>
        Hello Thymeleaf!
        <div th:include="../templates/footer :: footer"></div>
    </body>

    文件路径

    访问

       

    8,th:src

    用于外部资源引入,类似于<script>标签的src属性,常与@{}一起使用。

    <script th:src="@{/js/jquery-3.2.1.js}"></script>

    9,th:text

    文本显示。

    <td class="text" th:text="${username}" ></td>

    10,th:value

    用于标签复制,类似<option>标签的value属性。

    <input type="text" class="form-control" name="name" placeholder="name" th:value="*{name}"/>

    11,th:switch

    默认属性default可以用*表示。

    <div th:switch="${user.role}">
      <p th:case="'admin'">User is an administrator</p>
      <p th:case="#{roles.manager}">User is a manager</p>
      <p th:case="*">User is some other thing</p>
    </div>

    常用属性表格:

    关键字

    功能介绍

    案例

    th:id

    替换id

    <input th:id="'xxx' + ${collect.id}"/>

    th:text

    文本替换

    <p th:text="${collect.description}">description</p>

    th:utext

    支持html的文本替换

    <p th:utext="${htmlcontent}">conten</p>

    th:object

    替换对象

    <div th:object="${session.user}">

    th:value

    属性赋值

    <input th:value="${user.name}" />

    th:with

    变量赋值运算

    <div th:with="isEven=${prodStat.count}%2==0"></div>

    th:style

    设置样式

    th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"

    th:onclick

    点击事件

    th:onclick="'getCollect()'"

    th:each

    属性赋值

    tr th:each="user,userStat:${users}">

    th:if

    判断条件

    <a th:if="${userId == collect.userId}" >

    th:unless

    和th:if判断相反

    <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

    th:href

    链接地址

    <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />

    th:switch

    多路选择 配合th:case 使用

    <div th:switch="${user.role}">

    th:case

    th:switch的一个分支

    <p th:case="'admin'">User is an administrator</p>

    th:fragment

    布局标签,定义一个代码片段,方便其它地方引用

    <div th:fragment="alert">

    th:include

    布局标签,替换内容到引入的文件

    <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />

    th:replace

    布局标签,替换整个标签到引入的文件

    <div th:replace="fragments/header :: title"></div>

    th:selected

    selected选择框 选中

    th:selected="(${xxx.id} == ${configObj.dd})"

    th:src

    图片类地址引入

    <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />

    th:inline

    定义js脚本可以使用变量

    <script type="text/javascript" th:inline="javascript">

    th:action

    表单提交的地址

    <form action="subscribe.html" th:action="@{/subscribe}">

    th:remove

    删除某个属性

    <tr th:remove="all"> 1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。

    th:attr

    设置标签属性,多个属性可以用逗号分隔

    比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。

  • 相关阅读:
    jquery从零开始(一)
    Android第三次作业
    Android第一次作业
    团队作业-项目答辩
    软工第二次作业
    软工团队第二次作业
    bug killer 团队
    软件工程第一次作业
    Android第四次作业
    Android第三次作业
  • 原文地址:https://www.cnblogs.com/Zender/p/8709031.html
Copyright © 2011-2022 走看看