上一篇博文介绍了如何使用Freemaker引擎搭建web项目,这一篇我们则看一下另外一个常见的页面渲染引擎Thymeleaf如何搭建一个web项目

推荐结合Freemaker博文一起查看,效果更佳 190816-SpringBoot系列教程web篇之Freemaker环境搭建

I. 准备

Thymeleaf 是现代化服务器端的Java模板引擎,不同与JSP和FreeMarker,Thymeleaf的语法更加接近HTML,关于它的使用说明,可以参考官方文档

https://www.thymeleaf.org/documentation.html

1. 依赖

首先我们是需要一个springboot项目,基本的pom结构大都相似

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from update -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<java.version>1.8</java.version>
</properties> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>

在这个项目中,我们主要需要引入两个依赖包,一个web,一个thymeleaf

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

2. 配置参数

通常我们直接使用默认的thymeleaf参数配置即可,下面给出几个常用的配置

spring:
thymeleaf:
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
cache: false

thymeleaf的参数,主要对应的是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties

II. 项目搭建演示

1. 项目结构

搭建一个web项目和我们之前的纯后端项目有点不一样,前端资源放在什么地方,依赖文件怎么处理都是有讲究的,下面是一个常规的项目结构

如上图,前端资源文件默认放在resources目录下,下面有两个目录

  • templates:存放模板文件,可以理解为我们编写的html,注意这个文件名不能有问题
  • static: 存放静态资源文件,如js,css,image等

2. Rest服务

我们这里提供了三个接口,主要是为了演示三种不同的数据绑定方式(和Freemaker这篇博文基本一样)

@Controller
public class IndexController { @GetMapping(path = {"", "/", "/index"})
public ModelAndView index() {
Map<String, Object> data = new HashMap<>(2);
data.put("name", "YiHui Thymeleaf");
data.put("now", LocalDateTime.now().toString());
return new ModelAndView("index", data);
} /**
* 一般不建议直接使用jdk的String.split来分割字符串,内部实现是根据正则来处理的,虽然更强大,但在简单的场景下,性能开销更大
*/
private static String[] contents =
("绿蚁浮觞香泛泛,黄花共荐芳辰。\n清霜天宇净无尘。\n登高宜有赋,拈笔戏成文。\n可奈园林摇落尽,悲秋意与谁论。\n眼中相识几番新。\n龙山高会处,落帽定何人。").split("\n");
private static Random random = new Random(); @GetMapping(path = "show1")
public String showOne(Model model) {
model.addAttribute("title", "临江仙");
model.addAttribute("content", contents[random.nextInt(6)]);
return "show1";
} @GetMapping(path = "show2")
public String showTow(Map<String, Object> data) {
data.put("name", "Show2---->");
data.put("now", LocalDateTime.now().toString());
return "show2";
}
}

上面的三种case中

  • 第一个是最好理解的,在创建ModelAndView时,传入viewName和数据
  • 第二个是通过接口参数Model,设置传递给view的数据
  • 第三种则直接使用Map来传递数据

三个接口,对应的三个html文件,如下

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="SpringBoot thymeleaf"/>
<meta name="author" content="YiHui"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>YiHui's SpringBoot Demo</title>
<link rel="stylesheet" href="index.css"/>
</head>
<body> <div>
<div class="title">hello world!</div>
<br/>
<div class="content" th:text="'欢迎访问' + ${name}">默认的内容</div>
<br/>
<div class="sign" th:text="'当前时间' + ${now}">默认的签名</div>
<br/>
<a href="show1">传参2测试</a> &nbsp;&nbsp;&nbsp;&nbsp;
<a href="show2">传参3测试</a>
</div>
</body>
</html>

show1.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="SpringBoot thymeleaf"/>
<meta name="author" content="YiHui"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>YiHui's SpringBoot Demo</title>
<link rel="stylesheet" href="index.css"/>
</head>
<body> <div>
<div class="title" th:text="${title}">标题!</div>
<div class="content" th:text="${content}">内容</div>
</div>
</body>
</html>

show2.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="SpringBoot thymeleaf"/>
<meta name="author" content="YiHui"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>YiHui's SpringBoot Demo</title>
<link rel="stylesheet" href="index.css"/>
</head>
<body> <div>
<div class="title" th:text="${name}">标题!</div>
<div class="content" th:text="${now}">内容</div>
</div>
</body>
</html>

在上面的模板文件中,需要注意引用css样式文件,路径前面并没有static,我们对应的css文件

index.css

.title {
color: #c00;
font-weight: normal;
font-size: 2em;
} .content {
color: darkblue;
font-size: 1.2em;
} .sign {
color: lightgray;
font-size: 0.8em;
font-style: italic;
}

3. 演示

启动项目后,可以看到三个页面的切换,模板中的数据根据后端的返回替换,特别是主页的时间,每次刷新都会随之改变

II. 其他

0. 项目&系列文章

1. 一灰灰Blog

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

下面一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

SpringBoot系列教程web篇之Thymeleaf环境搭建的更多相关文章

  1. SpringBoot系列教程web篇之Beetl环境搭建

    前面两篇分别介绍了目前流行的模板引擎Freemaker和Thymeleaf构建web应用的方式,接下来我们看一下号称性能最好的国产模板引擎Beetl,如何搭建web环境 本文主要来自官方文档,如有疑问 ...

  2. SpringBoot系列教程web篇之Freemaker环境搭建

    现在的开发现状比较流行前后端分离,使用springboot搭建一个提供rest接口的后端服务特别简单,引入spring-boot-starter-web依赖即可.那么在不分离的场景下,比如要开发一个后 ...

  3. SpringBoot系列教程web篇之过滤器Filter使用指南扩展篇

    前面一篇博文介绍了在 SpringBoot 中使用 Filter 的两种使用方式,这里介绍另外一种直接将 Filter 当做 Spring 的 Bean 来使用的方式,并且在这种使用方式下,Filte ...

  4. SpringBoot系列教程Web篇之开启GZIP数据压缩

    本篇可以归纳在性能调优篇,虽然内容非常简单,但效果可能出乎预料的好: 分享一个真实案例,我们的服务部署在海外,国内访问时访问服务时,响应有点夸张:某些返回数据比较大的接口,耗时在 600ms+上,然而 ...

  5. SpringBoot系列教程web篇Listener四种注册姿势

    java web三要素Filter, Servlet前面分别进行了介绍,接下来我们看一下Listener的相关知识点,本篇博文主要内容为SpringBoot环境下,如何自定义Listener并注册到s ...

  6. SpringBoot系列教程web篇Servlet 注册的四种姿势

    原文: 191122-SpringBoot系列教程web篇Servlet 注册的四种姿势 前面介绍了 java web 三要素中 filter 的使用指南与常见的易错事项,接下来我们来看一下 Serv ...

  7. SpringBoot系列教程web篇之过滤器Filter使用指南

    web三大组件之一Filter,可以说是很多小伙伴学习java web时最早接触的知识点了,然而学得早不代表就用得多.基本上,如果不是让你从0到1写一个web应用(或者说即便从0到1写一个web应用) ...

  8. SpringBoot系列教程web篇之自定义异常处理HandlerExceptionResolver

    关于Web应用的全局异常处理,上一篇介绍了ControllerAdvice结合@ExceptionHandler的方式来实现web应用的全局异常管理: 本篇博文则带来另外一种并不常见的使用方式,通过实 ...

  9. SpringBoot系列教程web篇之全局异常处理

    当我们的后端应用出现异常时,通常会将异常状况包装之后再返回给调用方或者前端,在实际的项目中,不可能对每一个地方都做好异常处理,再优雅的代码也可能抛出异常,那么在 Spring 项目中,可以怎样优雅的处 ...

随机推荐

  1. 在linux下crontab不执行原因排查

    一.开启cron日志 #检查是否已经开启 cron sudo service cron status #cron start/running, process 23719 # 重启服务 cron su ...

  2. 8、Python简单数据类型(int、float、complex、bool、str)

    一.数据类型分类 1.按存值个数区分 单个值:数字,字符串 多个值(容器):列表,元组,字典,集合 2.按可变不可变区分 可变:列表[],字典{},集合{} 不可变:数字,字符串,元组().bool, ...

  3. PyInstaller库,打包成exe基本介绍

    一.pyinstaller简介 Python是一个脚本语言,被解释器解释执行.它的发布方式: .py文件:对于开源项目或者源码没那么重要的,直接提供源码,需要使用者自行安装Python并且安装依赖的各 ...

  4. List.Sort

    static void Main(string[] args) { List<double> valuesList = new List<double>(); valuesLi ...

  5. C++对象内存模型1(堆栈模型)(转)

    对象内存模型 一. 栈(Stack) VS. 堆(heap) 栈 由系统自动管理,以执行函数为单位 空间大小编译时确定(参数+局部变量) 函数执行时,系统自动分配一个stack 函数执行结束时,系统立 ...

  6. Wiki with Herbal Medicine

    Problem H. Wiki with Herbal MedicineInput file: standard input Time limit: 1 secondOutput file: stan ...

  7. 输入一个正整数n,生成一张2的乘方表,输出2*0—2*n的值。

    #include<stdio.h>#include<math.h> //程序中调用幂函数pow(),需包含头文件math.h//void main(){ int i,n; pr ...

  8. 2020年假期sql excel文件 获取

    下载地址: https://files.cnblogs.com/files/shmily3929/2020.zip 说明:sql 不区分节假期和周六周末   excel文件区分节假日和周六周末

  9. php 正则达达示中的模式修正符

    我们通过元字符和原子完成了正则表达示的入门.有一些特殊情况我们依然需要来处理.深圳dd马达 如果abc在第二行的开始处如何匹配?我不希望正则表达示特别贪婪的匹配全部,只匹配一部份怎么办? 这个时候,我 ...

  10. [RN] React Native 下实现底部标签(不支持滑动切换)

    底部标签是现在App的基本菜单实现 下面分别用 createBottomTabNavigator 和 createMaterialBottomTabNavigator 两种方法分别实现底部菜单 但此两 ...