Thymeleaf

本文介绍了Thymeleaf作为SpringMVC的视图解析器的配置和使用方法,包括依赖引入、模板解析器配置、HTML命名空间、以及如何使用Thymeleaf表达式显示和遍历数据。通过示例展示了如何展示实体类属性、遍历数组、列表和Map等操作。
摘要由CSDN通过智能技术生成

1:Thymeleaf

thymeleaf官方使用文档

之前在写SSM整合时,用到了Thymeleaf的视图解析器,还是不太熟悉,不过能做到将后端的数据展示在页面上。想深入学习的可以看上面的官方文档。

2:自己用的一部分

依赖:

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf-spring5</artifactId>
  <version>3.0.12.RELEASE</version>
</dependency>

SpringMVC视图解析器配置:

<!--thymeleaf视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="order" value="1"/><!-- 设置视图解析器的优先级 -->
    <property name="characterEncoding" value="UTF-8"/><!-- 视图解析编码 -->
    <property name="templateEngine" ><!-- 视图模板 -->
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!-- 视图前缀  html资源在templates包下-->
                    <property name="prefix" value="/WEB-INF/templates/"/>
                    <!-- 视图后缀 -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />
                </bean>
            </property>
        </bean>
    </property>
</bean>

html引入名称空间:

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

使用${}取值:
实体类对象:

<span th:text="'Thymeleaf通过${变量.属性}获取属性值='+${user.name}+'!!!'"/>
<br/>
<span th:text="'Thymeleaf通过${变量.属性}获取属性值='+${user.id}+'!!!'"/>

使用th:Object引用${}中的变量,用*代替该变量

<br/>
使用*表示变量th:Object="${变量}"中的内容:
<br/>
<div th:object="${user}">
    <span th:text="*{id}"/>
    <br/>
    <span th:text="*{name}"/>
</div>

array:

<br/>
使用th:each="i : ${array}"遍历array:
<tr th:each="i :${array}">
    <th th:text="${i}"></th>
</tr>

list:

<br/>
使用th:each="i : ${list}"遍历list:
<tr th:each="user:${list}">
    <th th:text="${user.name}"/>
    <th th:text="${user.id}"/>
</tr>

map:

<ul>
    <li th:each="entry: ${map}">
        <span th:text="${entry.key}"></span> = <span th:text="${entry.value}"></span>
        <span th:object="${entry.value}">
            <span th:text="*{name}"/>
            <span th:text="*{id}"/>
        </span>
    </li>
</ul>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值