Thymeleaf简介

Thymeleaf简介

Thymeleaf简介

Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。

Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。需要注意的是thymeleaf不是spring旗下的。这里我们使用thymeleaf 3版本。
第一个thymeleaf程序
添加thymeleaf依赖

org.springframework.boot spring-boot-starter-thymeleaf

修改spring boot配置文件

在开发阶段,建议关闭thymeleaf的缓存

spring.thymeleaf.cache=false

thymeleaf会对html中的标签进行严格校验,如果html标签缺少结束标签的话,thymeleaf会报错,我们可以通过下面方式去除thymeleaf的校验,添加依赖:

net.sourceforge.nekohtml nekohtml 1.9.22

在spring boot配置文件中添加下面内容:

spring.thymeleaf.mode=LEGANCYHTML5

创建controller准备数据

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ThymeleafController {
@RequestMapping("/hello")
public String helloThymeleaf(Model model) {
model.addAttribute(“name”, “jack”);
return “index”;
}

}

创建html页面

在resources/templates里面创建一个index.html,填写下面内容,注意添加这个xmlns:th=“http://www.thymeleaf.org”:

Spring boot集成 Thymeleaf

Spring boot集成 Thymeleaf

Springboot使用thymeleaf作为视图展示的时候,我们将模板文件放置在resource/templates目录下,静态资源放置在resource/static目录下。
表达式
标准变量表达式

创建用来准备数据的Controller

@RequestMapping(value="/userInfo")
public String userInfo (Model model) {
User user = new User();
user.setId(1001);
user.setName(“jack”);
user.setPhone(“13711111111”);
model.addAttribute(“user”, user);
model.addAttribute(“hello”, “helloworld”);
return “user”;
}

创建user.html,通过th:text表达式来获取controller中返回的数据。

Spring boot集成 Thymeleaf
1a137

选择变量表达式

这里相当于是先使用th:object将user对象取出,然后在里面的th:text中获取user对象中的属性值。

1a137

url表达式

将后台传入的数据拼接到url中

参数拼接
多参数拼接
restful风格
restful风格

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值