SpringBoot2.X基础教程:SpringBoot整合Thymeleaf

微信号:hzy1014211086,如果你正在学习Spring Boot,可以加入我们的Spring技术交流群,共同成长


对于Web项目来说,前后端分离模式是目前最为流行的,目前前端框架非常完善,前后端分离方案也非常成熟。前后端分离可以帮助Web类产品的开发团队更好的拆分任务,以及让开发人员更加聚焦在某一端的开发技术之上。但是据我了解,小部分中小型公司的管理后台前后端是不分离的,而在前后端不分的开发中,我们就会需要用到Thymeleaf。

接下来,我们就来具体讲讲在Spring Boot应用中,如何使用Thymeleaf模板引擎开发Web页面类的应用。

一、静态文件

当使用Spring Boot来开发一个完整的系统时,我们往往需要用到前端页面,这就不可或缺地需要访问到静态资源,比如图片、css、js等文件。

Spring Boot使用 WebMvcAutoConfiguration 中的配置各种属性, 默认为我们提供了静态资源处理。如果需要特殊处理的再通过配置进行修改。

SpringBoot 框架默认提供的静态资源目录的位置需放置于 classpath下,且要求了命名的规范,目录名应遵守的命名规范如下:

  • /static
  • /public
  • /resources
  • /META-INF/resources

二、模板引擎

除了 REST web 服务之外,您还可以使用 Spring MVC 来服务动态 HTML 内容。Spring MVC 支持多种模板技术,包括 Thymeleaf、FreeMarker 和 JSP。当然,许多其他模板引擎也有自己的 Spring MVC 集成。

Spring Boot支持多种模版引擎包括:

  • FreeMarker
  • Groovy
  • Thymeleaf(官方推荐)
  • Mustache

JSP技术Spring Boot官方是不推荐的,原因有四:

  • tomcat 只支持 war 的打包方式,不支持可执行的 jar。
  • Jetty 嵌套的容器不支持 jsp。
  • Undertow 不支持 JSP。
  • 创建自定义 error.jsp 页面不会覆盖错误处理的默认视图,而应该使用自定义错误页面

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

三、Thymeleaf模板引擎

Thymeleaf是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎,适用于 Web 和独立环境的现代服务器端 Java 模板引擎,它跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个特点:

  • Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 Thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL表达式效果,避免每天套模板、改 Jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

四、引入依赖

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

五、编写controller

在前面的几篇文章中,我们都是使用了 @RestController 来处理请求,返回的内容为 JSON 对象,那么如果需要渲染 html 页面,要如何实现呢?

@Controller
public class TestController {

  /**
   * 方案一
   * @param model
   * @return
   */
  @GetMapping("index1")
  public String index(Model model) {
    model.addAttribute("id", "1");
    model.addAttribute("title", "SpringBoot Thymeleaf");
    model.addAttribute("author", "Java程序鱼");
    return "index1";
  }

  /**
   * 方案二
   * @return
   */
  @GetMapping("index2")
  public Object index2() {
    ModelAndView modelAndView = new ModelAndView("/index2");

    modelAndView.addObject("id", "2");
    modelAndView.addObject("title", "SpringBoot Thymeleaf2");
    modelAndView.addObject("author", "Java程序鱼");
    return modelAndView;
  }

  /**
   * 方案三
   * @param modelMap
   * @return
   */
  @GetMapping("index3")
  public String index3(ModelMap modelMap) {
    modelMap.addAttribute("id", "3");
    modelMap.addAttribute("title", "SpringBoot Thymeleaf3");
    modelMap.addAttribute("author", "Java程序鱼");
    return "index3";
  }
}

六、编写html

在 src/main/resources/templates 下创建index1.html、index2.html、index3.html三个文件,代码都一样。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>index1</title>
</head>
<body>
    <th th:text="${id}">id</th>
    <th th:text="${title}">title</th>
    <th th:text="${author}">author</th>
</body>
</html>

在这里插入图片描述

七、语法

th:each

Thymeleaf 中使用 th:each 来进行 for 循环遍历

@Controller
public class BlogController {

  @GetMapping("each")
  public String each(Model model) {
    ArrayList<Blog> list = new ArrayList<>();
    list.add(new Blog(1, "each1", "java程序鱼1"));
    list.add(new Blog(2, "each2", "java程序鱼2"));
    list.add(new Blog(3, "each3", "java程序鱼3"));

    model.addAttribute("list", list);
    return "each";
  }
}

【each.html】

<body>
	<table>
	    <thead>
	    <tr>
	        <th>ID</th>
	        <th>标题</th>
	        <th>作者</th>
	    </tr>
	    </thead>
	    <tbody>
	    <tr th:each="item:${list}">
	        <td th:text="${item.id}"></td>
	        <td th:text="${item.title}"></td>
	        <td th:text="${item.author}"></td>
	    </tr>
	    </tbody>
	</table>
</body>

在这里插入图片描述

th:if

Thymeleaf 中使用 th:if 和 th:unless 属性进行条件判断,th:if 是表达式中的条件成立显示内容,th:unless 是表达式中的条件不成立才显示内容。

@Controller
public class BlogController {
  @GetMapping("if")
  public String ifHtml(Model model) {
    model.addAttribute("id", 1);
    return "if";
  }
}

【if.html】

<body>
    <div th:if="${id == 1}">th:if id==1</div>
    <div th:if="${id != 1}">th:if id!=1</div>

    <div th:unless="${id == 1}">th:unless id==1</div>
    <div th:unless="${id != 1}">th:unless id!=1</div>
</body>

在这里插入图片描述

th:replace&th:include

th:include,布局标签,替换内容到引入的文件
th:replace,布局标签,替换整个标签到引入的文件

我们在开发中需要把通用的部分都提取出来,例如文章的头部和底部,把文章的头部和底部弄成单独的页面,然后让其他页面包含头部和底部,这就是代码复用思维。

【include.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf include</title>
</head>
<body>
    <!--  语法说明  "::"前面是模板文件名,后面是选择器 -->
    <div class="commonHead" th:replace="commonHead::commonHead"></div>
    博客正文
    <div class="commonFooter" th:replace="commonFooter::commonFooter"></div>
</body>
</html>

【commonFooter.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>通用代码-底部</title>
</head>
<body>
    <div class="commonFooter" th:fragment="commonFooter">
        博客的底部
    </div>
</body>
</html>

【commonHead.html】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>通用代码-头部</title>
</head>
<body>
    <div class="commonHead" th:fragment="commonHead">
        博客的头部
    </div>
</body>
</html>

在这里插入图片描述

八、Thymeleaf的默认参数配置

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

# THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值:true)
spring.thymeleaf.cache=true 
#Check that the template exists before rendering it.
spring.thymeleaf.check-template=true 
#检查模板位置是否正确(默认值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默认值:text/html)
spring.thymeleaf.content-type=text/html
#开启MVC Thymeleaf视图解析(默认值:true)
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的视图名称列表,用逗号分隔
spring.thymeleaf.excluded-view-names=
#要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)
spring.thymeleaf.mode=HTML5
#在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在构建URL时添加到视图名称后的后缀(默认值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。
spring.thymeleaf.template-resolver-order=
#可解析的视图名称列表,用逗号分隔
spring.thymeleaf.view-names=

更多Thymeleaf的页面语法,可以访问Thymeleaf的官方文档来深入学习使用。

九、源码

本文的相关例子可以查看下面仓库中的 chapter3 目录:

  • Gitee:https://gitee.com/hezhiyuan007/spring-boot-study
  • Github:https://github.com/java-fish-0907/spring-boot-study
  • 14
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
## springboot整合thymeleaf ### 1. 导入起步依赖 ```xml org.springframework.boot spring-boot-starter-thymeleaf ``` ### 2. 更改引入版本 ```xml 3.0.2.RELEASE 2.1.1 ``` > 1. springboot自带的thymeleaf依赖为2.1.3版本,使用thymeleaf-layout-dialect版本为2以下版本。 > 2. 使用3或3以上的thymeleaf时,需要thymeleaf-layout-dialect的版本为2或以上。 > 3. 锁定thymeleaf版本时不能使用thymeleaf.version标签,会和springboot内部的依赖标签冲突。应当使用springboot-thymeleaf.version标签来锁定版本。 ### 3. 配置文件配置 ```properties spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.check-template-location=true spring.thymeleaf.suffix=.html spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.thymeleaf.mode=HTML spring.thymeleaf.cache=false ``` > spring.thymeleaf.cache为缓存,需要热部署时,需要设置为false ## 语法 ### 1. 替换标签体内容 ```html 显示欢迎 显示欢迎 ``` ### 2. 替换属性 ```html 显示欢迎 ``` ### 3. 在表达式中访问属性域 ```html 访问属性域 访问请求域 方式一 访问请求域 方式二 访问Session域 访Session域 方式一 访问Application域 方式一 ``` ### 4. 解析url地址 ```html 解析URL地址,获取ContextPath的值 @{}是把ContextPath的值附加到指定的地址前 @{}是把ContextPath的值附加到指定的地址前 ``` ### 5. 直接执行表达式 ```html 直接执行表达式 无转义效果 : [[${attrRequestScope}]] 有转义效果 : [(${attrRequestScope})] ``` ### 6. 分支与迭代 #### 1. if 判断 ```html if判断字符串是否为空 <p th

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java程序鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值