1: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>