如何使用Thymeleaf模板引擎将输入的id传递给BookController的GET请求方法并将内容显示在该页面上
要将输入的id传递给BookController的GET请求方法,并将内容显示在页面上,可以按照以下步骤操作:
- 在HTML模板文件中,使用Thymeleaf的表达式语法将用户输入的id绑定到表单的提交按钮上,例如:
<form action="#" th:action="@{/books}" method="get">
<input type="text" th:field="${id}" placeholder="Enter book id">
<button type="submit">Submit</button>
</form>
- 在BookController中创建GET请求方法,接收id作为参数,例如:
@GetMapping("/books")
public String getBookById(@RequestParam("id") String id, Model model) {
// 根据id查询书籍信息
Book book = bookService.getBookById(id);
// 将查询到的书籍信息添加到Model中
model.addAttribute("book", book);
// 返回模板文件名
return "book";
}
- 在book.html模板文件中,使用Thymeleaf的表达式语法将查询到的书籍信息显示在页面上,例如:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book Details</title>
</head>
<body>
<h1>Book Details</h1>
<div th:if="${book != null}">
<p>ID: <span th:text="${book.id}"></span></p>
<p>Title: <span th:text="${book.title}"></span></p>
<p>Author: <span th:text="${book.author}"></span></p>
<!-- 其他书籍信息 -->
</div>
<div th:if="${book == null}">
<p>No book found with ID: <span th:text="${id}"></span></p>
</div>
</body>
</html>
在用户输入id并点击提交按钮后,Thymeleaf会将输入的id作为请求参数传递给BookController的GET请求方法,该方法根据id查询书籍信息,并将查询结果添加到Model中。然后,Thymeleaf会根据模板文件book.html中的表达式语法,将书籍信息显示在页面上。如果没有找到匹配的书籍,页面会显示相应的提示信息
原文地址: https://www.cveoy.top/t/topic/hUBh 著作权归作者所有。请勿转载和采集!