Springboot 使用 thymeleaf

一、pom.xml 中引入 thymeleaf 依赖

<properties>
	<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
	<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

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

我们引入依赖 spring-boot-starter-thymeleaf 时, IDEA 会为我们自动下载匹配的 thymeleaf 版本,但是有时候版本比较低,不符合我们的要求,如果我们想要切换 thymeleaf 的版本,需要在 <properties> 标签中限定 thymeleaf 的版本,同时引入相对应的 thymeleaf-layout-dialect 版本 

需要注意一点 

thymeleaf 3.x 版本匹配 thymeleaf-layout-dialect 2.x 版本

thymeleaf 2.x 版本匹配 thymeleaf-layout-dialect 1.x 版本

二、编写控制器及跳转方法

@Controller
public class HelloWorldController {

    @RequestMapping("/success")
    public ModelAndView success(ModelAndView mav){
        mav.addObject("message","xiaomaomao");
        mav.setViewName("success");
        return mav;
    }
}

  

三、在 src/main/resources/templates 下创建一个测试页面 success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>xiao mao mao !!!</title>
</head>
<body>
    <h1>成功!</h1>
    <div th:text="${message}">welcome success page!!!</div>
</body>
</html>

 注意:需要在 html 标签上面添加命名空间 xmlns:th="http://www.thymeleaf.org" ,否则 thymeleaf 的自定义标签就没有提示

四、测试

五、原理及自定义

springboot 对 thymeleaf 自动配置的内容都在 org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.class 这个类中,我们打开这个类可以看到

@EnableConfigurationProperties 注解的作用就是将 Springboot 的配置文件 application.properties 中的配置与 ThymeleafProperties 这个类的属性进行绑定,打开这个类

从这里可以看出 springboot 对 thymeleaf 的默认配置方案,前缀是 classpath:/templates/ ,后缀是 .html

也就是说 springboot 默认情况下会去对 classpath:/templates/xxx.html 页面进行渲染

我们也可以通过修改 application.properties 中的配置来达到自定义 springboot 对 thymeleaf 解析的方案

// 修改访问路径的前缀,将原来默认的 classpath:/templates/ 修改为 classpath:/xiaomaomao/templates/
// 这样 springboot 就会去 classpath:/xiaomaomao/templates/ 路径下寻找对应的 .html 文件进行渲染
spring.thymeleaf.prefix=classpath:/xiaomaomao/templates/

六、thymeleaf 常用配置

// 开启 thymeleaf 视图解析	
spring.thymeleaf.enabled=true
// 编码格式
spring.thymeleaf.encoding=utf-8
// 前缀
spring.thymeleaf.prefix=classpath:/templates/
// 后缀
spring.thymeleaf.suffix=.html
// 是否使用缓存
spring.thymeleaf.cache=false
// 模式(严格的 HTML 语法模式)
spring.thymeleaf.mode=HTML

  

  

原文地址:https://www.cnblogs.com/xiaomaomao/p/13998588.html