SpringBoot集成Thymeleaf
JSP的缺点
JSP会被编译成为Servlet,重量级。
JSP的缺点就是模板的优点。
除Thymeleaf,还有哪些模板
理论
SpringBoot模板默认配置的目录是templates
。
操作
-
引入Thymeleaf依赖(pom.xml)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
添加配置(可省略,则使用默认配置)
spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html
-
代码开发和页面效果测试
controller层:添加一个
PageController
类package com.yeyouluo.hellospringboot.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * @Auther: yeyouluo * @Date: 2020/5/23 */ @Controller public class PageController { @RequestMapping("/index") public String index(Model model) { model.addAttribute("name", "yeyouluo"); return "index"; } }
在
resources/templates
目录下新建一个HTML5页面index.html
,内容如下:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试页面</title> </head> <body> <h1>hello,Thymeleaf</h1> <p>by <span th:text="${name}"></span></p> </body> </html>
-
启动查看效果
其他收获
- 可以使用
Model
传递给页面参数。页面使用${xxx}
获取(Thymeleaf
语法)。 Thymeleaf
基础知识(整理自https://www.jianshu.com/p/908b48b10702)