Thymeleaf简介
Thymeleaf简介
Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。
Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。需要注意的是thymeleaf不是spring旗下的。这里我们使用thymeleaf 3版本。
第一个thymeleaf程序
添加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
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中返回的数据。
1 | a | 137 |
选择变量表达式
这里相当于是先使用th:object将user对象取出,然后在里面的th:text中获取user对象中的属性值。
1 | a | 137 |
url表达式
将后台传入的数据拼接到url中