Spring Boot 系列之 thymeleaf

来源:互联网 发布:office办公软件技巧 编辑:程序博客网 时间:2024/06/04 23:11

在spring-boot1.4之后,支持thymeleaf3,可以更改版本号来进行修改支持. 
3相比2极大的提高了效率,并且不需要标签闭合,类似的link,img等都有了很好的支持,按照如下配置即可

1.引入依赖

maven中直接引入
<properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>    <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version></properties>


    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-thymeleaf</artifactId>    </dependency>

2.配置视图解析器

spring-boot很多配置都有默认配置,比如默认页面映射路径为 
classpath:/templates/*.html 
同样静态文件路径为 
classpath:/static/

在application.properties中可以配置thymeleaf模板解析器属性

#thymeleaf startspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8spring.thymeleaf.content-type=text/html#开发时关闭缓存,不然没法看到实时页面spring.thymeleaf.cache=false#thymeleaf end

3.编写DEMO
 @GetMapping("/hello")     public String hello(Model model) {         model.addAttribute("name", "Dear");         return "hello";     }

页面
<!DOCTYPE HTML><html xmlns:th="http://www.thymeleaf.org"><head>    <title>hello</title>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><p th:text="'Hello, ' + ${name}" ></p><br></body></html>


4.基础语法

首先要在改写html标签
<html xmlns:th="http://www.thymeleaf.org">

1.获取变量值

<p th:text="'Hello, ' + ${name}" ></p><br>

2.引入URL 条件判断 if /unless

Thymeleaf对于URL的处理是通过语法@{…}来处理的

<a th:href="@{http://baidu.com}">绝对路径,超链接</a><a th:href="@{css/a.css}">Content路径,默认访问static下的css文件夹</a>if 条件判断<a th:href="@{/}" th:if="${users != null}">Login</a>


3.循环

<table><tr><th>名称</th><th>年龄</th></tr><tr th:each="user:${users}"><td th:text="${user.name}">oname</td><td th:text="${user.age}">12</td></tr></table>




更多资料参考:
https://www.cnblogs.com/ityouknow/p/5833560.html

http://blog.csdn.net/u012706811/article/details/52185345