在基于Thymeleaf的Spring Boot应用程序中,从一个页面传递数据到另一个页面可以通过多种方式实现。以下是几种常见的方法:
这是最简单和最常用的方法。你可以在控制器中将数据添加到Model对象中,然后在Thymeleaf模板中访问这些数据。
控制器:
@Controller
public class MyController {
@GetMapping("/page1")
public String page1(Model model) {
model.addAttribute("message", "Hello from Page 1");
return "page1";
}
@GetMapping("/page2")
public String page2() {
return "page2";
}
}
page1.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 1</title>
</head>
<body>
<h1 th:text="${message}"></h1>
<a th:href="@{/page2(message=${message})}">Go to Page 2</a>
</body>
</html>
page2.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 2</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
你可以将数据作为URL参数传递,然后在目标页面中通过Thymeleaf表达式获取这些参数。
控制器:
@Controller
public class MyController {
@GetMapping("/page1")
public String page1() {
return "page1";
}
@GetMapping("/page2")
public String page2(@RequestParam("message") String message, Model model) {
model.addAttribute("message", message);
return "page2";
}
}
page1.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 1</title>
</head>
<body>
<h1>Hello from Page 1</h1>
<a th:href="@{/page2(message='Hello from Page 1')}">Go to Page 2</a>
</body>
</html>
page2.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 2</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
如果你需要在多个请求之间共享数据,可以使用Session。
控制器:
@Controller
public class MyController {
@GetMapping("/page1")
public String page1(HttpSession session) {
session.setAttribute("message", "Hello from Page 1");
return "page1";
}
@GetMapping("/page2")
public String page2(HttpSession session, Model model) {
String message = (String) session.getAttribute("message");
model.addAttribute("message", message);
return "page2";
}
}
page1.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 1</title>
</head>
<body>
<h1>Hello from Page 1</h1>
<a th:href="@{/page2}">Go to Page 2</a>
</body>
</html>
page2.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Page 2</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
通过以上方法,你可以在基于Thymeleaf的Spring Boot应用程序中有效地从一个页面传递数据到另一个页面。
领取专属 10元无门槛券
手把手带您无忧上云