前端模板引擎:Thymeleaf

文章转自:https://blog.csdn.net/sinat_30254575/article/details/79515222

一、Thymeleaf 简介

1.1 Thymeleaf 使用背景

    虽然 JSP 已经使用了较长的时间,并且在 Java web 中使用的也很广泛,但是它也有自身的一些缺陷。明显的就是 JSP 是以HTML 或者 XML 的形式展现的。大多数的 JSP 模版都使用 HTML 的格式,并使用各种 JSP 标签库。虽然这些标签库可以在 JSP中进行动态的解析,但是却很难有一个格式良好的页面。比如,可以在 HTML 中使用下面的 JSP 标签:

<input type="text" value="<c:out value="${thing.name}"/>" />

    当阅读一个没有解析的 JSP 页面时,常常很难读懂,简直就是一场视觉灾难!因为 JSP 并不是真正的 HTML,很多 Web浏览器和编辑器很难对 JSP 进行解析。而且,JSP 与 servlet 规范是紧密耦合的,这就意味着它只能使用在以 Servlet 为基础的 Web应用中。

    近年内有涌现出很多要替代 JSP 作为 Java 应用的视图技术,其中一个有力的竞争者就是:Thymeleaf。Thymeleaf 不需要依赖标签库,并且是可编辑的、可以解析到 HTML 中。另外,它与 Servlet 规范是没有耦合的,因此它可以在 JSP 不能使用的环境进行使用。下面,我们来看一下如何在 Spring MVC 中使用 Thymeleaf。

1.2 Thymeleaf 介绍

    1、Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可。

    2、Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。

    3、Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。

    4、Thymeleaf主要通过HTML的标签属性渲染标签内容,浏览器在解析html时,当检查到Thymeleaf的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。

二、Thymeleaf 基本语法

    在 html 文件中使用 Thymelead 标签 需要在头文件中加入,否则无法使用它的标签。

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
2.1 基础表达式
2.1.1 变量表达式:${……}
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

    以上是 Html 内容,以下是 Java 后台传送数据到前台。

/**
 * 入门-thymeleaf基础语法:基础表达式 之 变量表达式
 * 语法:${conten}
 * @param model
 * @return
 */
@RequestMapping("basicExpression")
public String basicExpression(Model model){
    model.addAttribute("person",this.getPerson());
    return "basic_expression";
}
2.1.2 选择/星号表达式:*{……}
<div th:object="${person}">
    <p>Name:
    <span th:text="*{name}">Saturn</span>.
    </p>
    <p>Age:
        <span th:text="*{age}">30</span>.
    </p>
    <p>Phone:
        <span th:text="*{phone}">1350992····</span>.
    </p>
    <p>Address:
        <span th:text="*{address}">广州**科技</span>.
    </p>
</div>

    以上是 html 内容,以下是 java 后台传送数据到前台。

/**
 * 入门-thymeleaf基础语法:基础表达式 之 选择/星号表达式
 * 语法:  *{content}
 * 注意点: 需要配合th:object标签使用
 * @param model
 * @return
 */
@RequestMapping("selectExpression")
public String selectExpression(Model model){
    model.addAttribute("person",this.getPerson());
    return "basic_expression_selection";
}
2.1.3 文字国际化表达式:#{……}

    Thymeleaf文字国际化需要springmvc的支持:

    1、在资源目录 resources 下创建文件夹 spring-i18n 作为国际化文件的根目录,创建各种语言的 .properties文件存储需要使用的内容;

    2、在 Spring 配置文件中加入资源;

<!--配置thymeleaf文字国际化 -->
<bean id="messageSource"
     class="org.springframework.context.support.ResourceBundleMessageSource">
   <!-- 资源文件路径 -->
   <property name="basename" value="spring-i18n/messages"></property>
   <property name="defaultEncoding" value="UTF-8"/>
</bean>

    3、properties 文件内容

message.title=\u8fd9\u662f\u4e00\u4e2a\u6807\u9898

    4、加入 Html 代码

<h1 th:utext="#{message.title}">Hello World</h1>

    5、加入 Java 代码

/**
 * 入门-thymeleaf基础语法:基础表达式 之 文字国际化 i18n Internationalization
 * 语法:  #{content}
 * 注意点:需要springmvc配置好资源文件,注意中文编码格式
 * @return
 */
@RequestMapping("i18nExpression")
public String i18nExpression(){
    return "i18n_expression";
}

    可以看出,在后台代码中,我们没有处理相应的国际化资源文件,Thymeleaf会自动根据浏览器语言,从spring管理的国际化资源文件中选中合适的进行显示。

2.1.4 URL表达式:@{……}

    @{……} 支持绝对路径和相对路径。其中相对路径又支持跨上下文调用url和协议的引用。

    1、Html 代码

URL点击 :<a href="details.html" th:href="@{myThymeleaf(orderId=${id})}">view</a></br>
相对路径:<img th:width="100px" th:src="@{../images/{imageUrl}(imageUrl=${image})}"></br>
绝对路径:<img th:width="100px" th:src="@{/images/{imageUrl}(imageUrl=${image})}"></br>
<!-- 无效链接 -->
其他路径:<img th:width="100px" th:src="@{images/{imageUrl}(imageUrl=${image})}">

    2、Java 代码

/**
 * 入门-thymeleaf基础语法:基础表达式 之 url
 * 语法:  @{content}
 * 注意:对静态资源的处理,否则访问不到
 * @param model
 * @return
 */
@RequestMapping("urlExpression")
public String urlExpression(Model model){
    model.addAttribute("id",10);
    model.addAttribute("image","001.jpg");
    return "url_expression";
}

    3、注意:当我们在页面中访问服务器资源是,是会被拦截的,需要在 spring 中配置资源处理,才能访问静态资源。

<!-- 处理静态资源 -->
<mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
<mvc:resources mapping="/js/**" location="/js/"/>
2.2 Thymeleaf 常用标签
2.2.1 普通标签

    Thymeleaf中大部分标签都是与html原有属性对应的,比如html中script标签的src属性,在Thymeleaf中对应th:src标签,这样通过静态解析的时候,浏览器会读取src属性对应的js,而通过动态解析访问的时候,浏览器拿到的src即为th:src中的内容。

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>常用普通标签-ThymeLeaf 模板引擎</title>
</head>
<body>
<!--
    Thymeleaf中大部分标签都是与html原有属性对应的,比如html中script标签的src属性,在Thymeleaf中对应th:src标签
-->
    <!-- 引入iuput标签 -->
    <input type="text" name="name" th:value="ThymeleafValue" value="HtmlValue">
    <!-- 引入img标签 -->
    <img src="../images/001.jpg" width="200px" th:width="100px" th:src="@{../images/001.jpg}"></br>
    <!-- 引用javascript标签 -->
    <script type="text/javascript" src="../js/myThymeleaf.js" th:src="@{/js/myThymeleaf.js}"></script>
</body>
</html>
2.2.2 常用标签
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>常用普通标签-ThymeLeaf 模板引擎</title>
</head>
<body>
<!--
    Thymeleaf中大部分标签都是与html原有属性对应的,比如html中script标签的src属性,在Thymeleaf中对应th:src标签
-->
    <p>简单数据转换:</p>
    <dt>年龄</dt>
<!-- 此示例表示保留两位小数位,整数位1位,不够位自动补0; -->
    <dd th:text="${#numbers.formatDecimal(person.age, 1, 2)}">25</dd>
    <dt>生日</dt>
    <dd th:text="${#dates.format(person.birthday, 'yyyy-MM-dd')}">2014-12-01</dd>
    <p>字符串拼接</p>
    <dt>地址</dt>
    <dd th:text="${'广东省'+person.address}">越秀区</dd>
    <p>表单</p>
    <form th:action="@{/vic/person}" th:object="${person}" method="post" th:method="post">
        <!-- th:field常用于表单字段绑定。通常与th:object一起使用。 属性绑定、集合绑定。 -->
        <dt>姓名:<input type="text"  th:field="*{name}"/></dt>
        <dt>年龄:<input type="text" th:field="*{age}"/></dt>
        <dt>电话:<input type="text" th:field="*{phone}"/></dt>
        <dt>地址:<input type="text" th:field="*{address}"/></dt>
        <dt>生日:<input type="text" th:field="*{birthday}"/></dt>
        <dt><input type="submit"/>
    </form>
</body>
</html>

    th:field 表单字段的绑定是经常使用的,方便开发。

2.2.3 常用工具

    工具对象表达式。常用于日期、集合、数组对象的访问。这些工具对象就像是java对象,可以访问对应java对象的方法来进行各种操作。有#maps、#dates、#calendars、#numbers、#lists等。

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>工具对象-ThymeLeaf 模板引擎</title>
</head>
<body>
    <p>工具对象表达式。常用于日期、集合、数组对象的访问。
        这些工具对象就像是java对象,可以访问对应java对象的方法来进行各种操作。</p>
    <p>#maps、#dates、#calendars、#numbers、#lists等</p>
    <p>简单数据转换:</p>
    <dt>#numbers:年龄</dt><dd th:text="${#numbers.formatDecimal(person.age, 1, 2)}">25</dd>
    <dt>#dates:生日</dt><dd th:text="${#dates.format(person.birthday, 'yyyy-MM-dd')}">2014-12-01</dd>
    <dt>#calendars:生日</dt><dd th:text="${#calendars.format(person.birthday, 'dd MMMM yyyy')}">2014-12-01</dd>
    <div th:if="${#maps.isEmpty(persons)}">
        <p>#maps:判断对象是否为空</p>
    </div>
    <div>
        #lists:<span th:text="${#lists.size(personList)}"></span>
    </div>
    <!-- 变量必须在里面使用,否则无效 -->
    <div th:with="sizes=${#lists.size(personList)}">
        <h3>当前数据长度:<span th:text="${sizes}"></span></h3>
    </div>
    <div>
        <!-- 此参数必须经过地址栏传到 -->
        #httpServletRequest: <span th:text="${#httpServletRequest.getParameter('ids')}"></span>
    </div>
</body>
</html>
2.2.4 循环、if、switch
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>IF/EACH/SWITCH-ThymeLeaf 模板引擎</title>
</head>
<body>
    <div>
        <span th:if="${switch > 8}"> 判断大于8 显示</span>
        <span th:if="${switch > 32}"> 判断大于32 不显示</span>
    </div>
--------------------------------------------------
    <div>
        <span th:unless="${switch > 8}"> 判断大于8 显示</span>
        <span th:unless="${switch > 32}"> 判断大于32 不显示</span>
    </div>
    <div th:switch="${switch}">
        <p th:case="'admin'">User is an administrator</p>
        <p th:case="30">User is a manager</p>
        <p th:case="20">User is a manager</p>
        <!--默认情况-->
        <p th:case="*">User is some other thing</p>
    </div>
    -- 循环 --
    <div th:if="${personList!=null}">
        <table>
            <tr th:each="person : ${personList}">
                <td th:text="${person.name}"></td>
                <td th:text="${person.age}"></td>
                <td th:text="${person.address}"></td>
            </tr>
        </table>
    </div>
</body>
</html>

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值