Thymeleaf入门
一、创建一个Maven项目
如下创建了名为ctest_thymeleaf
项目
二、导入坐标
在pox.xml
加入thymeleaf
坐标
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/>
</parent>
<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>
三、测试
最后项目结构图:
在resources
下创建一个templates
目录,在该目录下创建hello.html
.
th:text=“key” 会将从控制器相应的key对应的value放置在该标签文本内
thymeleaf和html不同的是多了一行xmlns:th="http://www.thymeleaf.org
在hello.html
加入如下代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${sayHello}"> </div>
</body>
</html>
控制器类HelloController
:
package com.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/h")
public String he(Model model){
model.addAttribute("sayHello","Hello Thymeleaf!");
return "hello"; //返回 指定哪一个模板, 这个是上述的hello.html
}
}
SpringBoot启动类DemoApplication
:
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
运行DemoApplication
在浏览器输入http://localhost:8080/h
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。