`
白马探
  • 浏览: 14633 次
社区版块
存档分类
最新评论

Spring Boot :模版引擎 Thymeleaf 渲染 Web 页面

 
阅读更多

1. 什么是 Thymeleaf ?

虽然我们目前拥有许多十分优秀的前端框架,例如: Vue 、 React 等,非常适用于前后端分离的场景,前端可以独立部署成为服务,前后端从物理上完全进行隔离,降低程序耦合度。但是 Spring Boot 官方依然为我们提供了模版引擎用于一些无需前后端分离的场景。 Thymeleaf 是新一代的模板引擎,在 Spring Boot 中,官方推荐使用 Thymeleaf 来做前端模版引擎。打开 https://start.spring.io/ 可以看到,在当前Spring Boot 的版本中( 2.1.8.RELEASE ), 官方提供的模版引擎有以下几种:

  • Thymeleaf
  • FreeMarker
  • Mustache
  • Groovy

Spring Boot 建议使用这些模版引擎,而并不推荐我们继续使用 JSP 。

Thymeleaf 具体特性如下:

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

2. 快速入门(了解源码可+求求: 1791743380)

这里我们先正常构建一个 Spring Boot 工程: spring-boot-thymeleaf ,在 pom.xml 文件中引入 Thymeleaf 的相关依赖,如下:

Java代码 
  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  4. </dependency>  

 工程的配置文件 application.yml 如下:

Java代码 
  1. server:  
  2.   port: 8080  
  3. spring:  
  4.   application:  
  5.     name: spring-boot-thymleaf  
  6.   thymeleaf:  
  7.     # 关闭thymeleaf缓存 开发时使用 否则没有实时画面  
  8.     cache: false  
  9.     # 检查模板是否存在,然后再呈现  
  10.     check-template-location: true  
  11.     # Content-Type value.  
  12.     servlet:  
  13.       content-type: text/html  
  14.     # 启用MVC Thymeleaf视图分辨率  
  15.     enabled: true  
  16.     # Template encoding.  
  17.     encoding: UTF-8  
  18.     # 关闭严格模式  
  19.     mode: LEGACYHTML5  
  20.     # Prefix that gets prepended to view names when building a URL.  
  21.     prefix: classpath:/templates/  
  22.     # Suffix that gets appended to view names when building a URL.  
  23.     suffix: .html  
  24.   mvc:  
  25.     # 指定静态资源处理路径  
  26.     static-path-pattern: /static/**  
  27.     view:  
  28.       suffix: .html  

 

有关 thymeleaf 都写明了注释,这里需要注意的有以下几点:

  • spring.thymeleaf.mode :这里是配置当前模版的解析模式的,默认值为 HTML ,这时会开启严格模式,所有的 HTML 必须有头有尾,很多地方并不符合我们平时的书写习惯,这里最好关闭严格模式。
  • spring.thymeleaf.cache :这里是 thymeleaf 的缓存,在平时的练习中最好关闭,否则页面修改后刷新浏览器将会无效,而在生产环境中,视具体的业务场景而定。
  • spring.mvc.static-path-pattern :这里是配置我们静态资源的路径,一般默认是配置 /static/** 路径,这里用于存放我们的 js 、 css 、图片等静态资源。

配置通用 404 和 500 页面,直接在 templates\error 创建对应页面即可,这里可以看一下 Spring Boot 错误页面转发的源码 org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver,如下:

Java代码 
  1. @Override  
  2. public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {  
  3.     ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);  
  4.     if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {  
  5.         modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);  
  6.     }  
  7.     return modelAndView;  
  8. }  
  9.   
  10. private ModelAndView resolve(String viewName, Map<String, Object> model) {  
  11.     String errorViewName = "error/" + viewName;  
  12.     TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,  
  13.             this.applicationContext);  
  14.     if (provider != null) {  
  15.         return new ModelAndView(errorViewName, model);  
  16.     }  
  17.     return resolveResource(errorViewName, model);  
  18. }  

 

可以看到这里会根据当前的状态响应码转发到对应的页面,路由为 error/** 。笔者这里简单创建两个错误页面,如图:

 

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面
 

 

创建测试 Controller ,如下:

Java代码 
  1. @Controller  
  2. public class HelloController {  
  3.   
  4.     @GetMapping("/hello")  
  5.     public String hello(HttpServletRequest request) {  
  6.         // 构建测试数据  
  7.         Map<String, Object> map = new HashMap<>();  
  8.   
  9.         UserModel userModel = new UserModel();  
  10.         userModel.setId(1L);  
  11.         userModel.setName("Spring Boot");  
  12.         userModel.setAge(18);  
  13.   
  14.         map.put("user", userModel);  
  15.   
  16.         List<CourseModel> list = new ArrayList<>();  
  17.   
  18.         for (int i = 0; i < 2; i++) {  
  19.             CourseModel courseMode = new CourseModel();  
  20.             courseMode.setId((long) i);  
  21.             courseMode.setName("Spring Boot:" + i);  
  22.             courseMode.setAddress("课程地点:" + i);  
  23.             list.add(courseMode);  
  24.         }  
  25.   
  26.         map.put("list", list);  
  27.   
  28.         map.put("flag", true);  
  29.   
  30.         request.setAttribute("data", map);  
  31.         return "hello";  
  32.     }  
  33. }  

 

在此注册测试类中,进行数据初始化并输出至页面。

  • Thymeleaf 默认的模板路径 src/main/resources/templates ,只需要在这个这个路径下编写模版文件即可。

Thymeleaf 模版文件如下:

Java代码 
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml"  
  3.       xmlns:th="http://www.thymeleaf.org">  
  4. <head>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">  
  7.     <title>Hello Spring Boot</title>  
  8.     <link rel="stylesheet" th:href="@{/static/css/bootstrap.min.css}">  
  9. </head>  
  10. <body>  
  11. <div class="container">  
  12.     <div>用户信息:</div>  
  13.     <table class="table table-dark">  
  14.         <thead>  
  15.         <tr>  
  16.             <th scope="col">#</th>  
  17.             <th scope="col">姓名</th>  
  18.             <th scope="col">年龄</th>  
  19.         </tr>  
  20.         </thead>  
  21.         <tbody>  
  22.         <tr>  
  23.             <th scope="row" th:text="${data.user.id}"></th>  
  24.             <td th:text="${data.user.name}"></td>  
  25.             <td th:text="${data.user.age}"></td>  
  26.         </tr>  
  27.         </tbody>  
  28.     </table>  
  29.     <div>课程信息:</div>  
  30.     <table class="table table-dark">  
  31.         <thead>  
  32.         <tr>  
  33.             <th scope="col">#</th>  
  34.             <th scope="col">课程名称</th>  
  35.             <th scope="col">课程地点</th>  
  36.         </tr>  
  37.         </thead>  
  38.         <tbody>  
  39.         <tr th:each="course, iterStat : ${data.list}">  
  40.             <th scope="row" th:text="${course.id}"></th>  
  41.             <td th:text="${course.name}"></td>  
  42.             <td th:text="${course.address}"></td>  
  43.         </tr>  
  44.         </tbody>  
  45.     </table>  
  46.   
  47.     <div th:if="${data.flag == true}">如果 flag 为 true 你将可以看到这行字:)</div>  
  48.   
  49. </div>  
  50.   
  51. </body>  
  52. </html>  

 

Thymeleaf 部分常用 th 标签如下:

关键字 功能介绍 案例

th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替换 <p th:text="${collect.description}">description</p>
th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">conten</p>
th:object 替换对象 <div th:object="${session.user}">
th:value 属性赋值 <input th:value="${user.name}" />
th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:onclick="'getCollect()'"
th:each 属性赋值 tr th:each="user,userStat:${users}">
th:if 判断条件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判断相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路选择 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert">
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected选择框 选中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 图片类地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 删除某个属性 <tr th:remove="all"> 1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。
th:attr 设置标签属性,多个属性可以用逗号分隔 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}" ,此标签不太优雅,一般用的比较少。

3. 测试

启动当前工程,打开浏览器访问路径: http://localhost:8080/hello ,结果如图:

 

Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面
分享到:
评论

相关推荐

    spring boot+bootstrap+thymeleaf

    Spring Boot、Bootstrap和Thymeleaf是现代Web开发中常用的技术栈,它们分别在不同的层面上解决了开发效率和用户体验的问题。下面将详细解释这三个技术及其整合应用。 **Spring Boot** Spring Boot是由Pivotal团队...

    第2-3课:模板引擎 Thymeleaf 基础使⽤1

    Thymeleaf 是一款强大的Java模板引擎,尤其适合...总之,Thymeleaf作为一个强大的模板引擎,提供了优雅的模板设计方式和良好的开发体验,特别是在Spring Boot应用中,它是实现前后端数据绑定和动态页面渲染的理想选择。

    spring_boot使用的 模版引擎 thymeleaf3.0

    在Spring Boot项目中使用Thymeleaf作为模板引擎是目前Web开发中常见的实践之一,而Thymeleaf 3.0作为最新版本,已经广泛地集成在Spring MVC应用中,其功能和使用方式都成为开发人员必须掌握的技术要点。Thymeleaf是...

    Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图的方法

    Spring Boot与Kotlin结合使用Thymeleaf模板引擎渲染Web视图是一种常见的做法,尤其在构建现代化的MVC应用程序中。Thymeleaf是一个强大的、灵活的模板引擎,支持XML、XHTML和HTML5,其设计目标是提供一种在前端展示...

    spring boot+thymeleaf项目实战

    Spring Boot简化了Spring的配置,而Thymeleaf则是一个功能强大的服务器端模板引擎,为HTML页面提供了动态数据绑定和表达式语言。 首先,Spring Boot的核心特性包括自动配置、内嵌Web服务器(如Tomcat)以及起步依赖...

    spring boot+hibernate+thymeleaf 练习demo项目源码

    在本项目中,"spring boot+hibernate+thymeleaf 练习demo项目源码" 是一个基于Spring Boot框架、Hibernate ORM工具和Thymeleaf模板引擎的实践示例。这个小而精简的Demo旨在帮助学习者理解如何整合这三个核心技术来...

    基于spring boot 2集成hibernate及thymeleaf的简单实例

    在本文中,我们将深入探讨如何在Spring Boot 2框架中集成Hibernate ORM和Thymeleaf模板引擎,构建一个简单的Web应用程序。Spring Boot以其简洁的配置和开箱即用的特性,已经成为Java领域开发微服务和Web应用的首选。...

    spring boot+mybatis+thymeleaf 练习demo项目源码

    在本项目中,"spring boot+mybatis+thymeleaf 练习demo项目源码" 是一个基于Spring Boot、MyBatis和Thymeleaf技术栈构建的实践示例。这个项目旨在帮助开发者深入理解这三大框架的集成与应用,从而提升其在Web开发中...

    Spring MVC / Spring Boot中使用Thymeleaf模板引擎

    总的来说,Thymeleaf为Spring MVC和Spring Boot提供了强大的模板渲染能力,使得开发者可以专注于业务逻辑,而不需要关心复杂的视图层实现。结合Spring的注解驱动开发,Thymeleaf能极大地提高开发效率和代码的可维护...

    spring boot+thymeleaf+bootstrap 简单实现后台管理系统界面(看评论酌情下载)

    Thymeleaf 是一个现代的服务器端HTML模板引擎,特别适合Web应用的后端开发。它允许在HTML中直接编写模板,而无需额外的标记,使得页面更易于阅读和维护。Thymeleaf 在Spring Boot 中的整合,使得开发者能够方便地...

    spring-boot html thymeleaf

    1. **模板引擎集成**:Spring Boot 默认已经集成了 Thymeleaf,只需在配置文件中声明视图解析器即可。 2. **视图解析**:视图解析器会根据逻辑视图名(例如 "home")找到对应的模板文件(如 `src/main/resources/...

    spring boot+jpa+thymeleaf 练习demo项目源码

    通过分析和运行这个项目,开发者可以学习如何将Spring Boot的便利性、JPA的数据库操作以及Thymeleaf的动态页面渲染结合起来,构建一个功能齐全的Web应用程序。此外,还可以深入了解Spring Boot的自动配置、JPA的ORM...

    Spring boot+mybatis+thymeleaf 实现登录注册增删改查功能的示例代码

    使用Maven创建一个Spring Boot项目,`pom.xml`文件中包含了必要的依赖项,如Spring Boot的Web启动器、测试启动器、Thymeleaf启动器以及MyBatis的Spring Boot启动器。此外,还添加了MySQL的驱动依赖,以便连接到...

    Spring Boot+Mybatis+Thymeleaf+SQL Server实现简单增删改查

    Thymeleaf与Spring Boot结合,可以方便地实现前后端数据的绑定和页面渲染,使得动态内容展示更为直观和简洁。 4. **SQL Server**: SQL Server是Microsoft公司推出的关系型数据库管理系统,广泛应用于企业级数据...

    Spring+Spring Boot+JPA+Thymeleaf+Bootstrap+Mysql实现的一个单表crud

    这个应用的核心技术包括Spring、Spring Boot、JPA(Java Persistence API)、Thymeleaf模板引擎、Bootstrap前端框架以及Mysql数据库。下面将详细解释这些技术及其在项目中的作用。 **Spring** 是一个开源的应用程序...

    spring boot+mybatis+thymeleaf+apache shiro开发面向学习型的后台管理系统

    在本项目中,我们利用Spring Boot、MyBatis、Thymeleaf以及Apache Shiro这四个核心技术栈构建了一个面向学习型的后台管理系统。这个系统旨在提供一个高效、易用的平台,帮助用户进行学习资源的管理和分享。接下来,...

    采用Spring Boot + JPA + Thymeleaf实现的旅游之旅系统

    该系统整合了Spring Boot框架的快速开发特性、JPA技术的对象关系映射和数据库操作能力,以及Thymeleaf模板引擎的优雅页面渲染,为用户提供了便捷、高效的旅游信息浏览和预订服务。 旅游之旅系统为用户提供了多种...

    spring boot+thymeleaf+mybatis+mysql

    在本项目中,"spring boot+thymeleaf+mybatis+mysql" 是一个常见的Web应用开发框架组合,尤其适合初学者快速构建基于Java的Web应用程序。以下将详细阐述这四个关键技术及其整合过程中的关键知识点。 1. Spring Boot...

    spring boot+thymeleaf+bootstrap 简单实现后台管理系统界面

    在后台管理系统中,Thymeleaf可以方便地结合Spring Boot的模型数据,实现动态页面的渲染。 Bootstrap是Twitter推出的一个开源的前端框架,主要用于网页设计和开发。它提供了丰富的预定义样式、组件和JavaScript插件...

    Spring Boot + MyBatis + thymeleaf + MySQL + jQuery +ajax图书借阅管理系统

    Thymeleaf是一种现代的服务器端HTML模板引擎,它与Spring Boot整合后,可以方便地进行视图渲染。Thymeleaf允许开发者在HTML模板中直接写入逻辑表达式,使得前端页面动态化,同时保持了良好的可读性。 jQuery是...

Global site tag (gtag.js) - Google Analytics