发布时间:2024-01-23 17:00
创建springboot项目,导入Thymeleaf依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
Controller
@Controller
public class TestController {
@RequestMapping("t1")
public String hello() {
return "test";
}
}
在resources下创建templates文件夹,在文件夹下新建test.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>测试页面h1>
body>
html>
启动项目,访问http://localhost:8080/t1
编写controller
@RequestMapping("/t1")
public String test1(Model model){
//存入数据
model.addAttribute("msg","Hello,Thymeleaf");
//classpath:/templates/test.html
return "test";
}
html页面
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>标题title>
head>
<body>
<h1>测试页面h1>
<div th:text="${msg}">div>
body>
html>
启动测试:
再写一个controller
@RequestMapping("/t2")
public String test2(Map<String,Object> map){
//存入数据
map.put("msg","Hello
");
map.put("users", Arrays.asList("lisi","zhangsan"));
//classpath:/templates/test.html
return "test2";
}
创建一个新的test2.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>标题title>
head>
<body>
<h1>测试页面h1>
<div th:text="${msg}">div>
<div th:utext="${msg}">div>
<h4 th:each="user :${users}" th:text="${user}">h4>
<h4>
<span th:each="user:${users}">[[${user}]]span>
h4>
body>
html>
启动项目,访问 http://localhost:8080/t2