spring-boot - Show a list in index.html with Thymeleaf
问题描述
I'm using SpringBoot y Thymeleaf.
How could i do to display a list of product in index.html at the moment that page is loaded?
Currently products.html shows all the products from the bd and index.html shows the fragment with the header of the form of products.html but I do not know how to make to display the products.
if i'm wrong with my approach,how is the right way to do it?
index.html
<body>
<section layout:fragment="custom-content">
<br> <br>
<div class="container">
<section th:replace="products :: content"></section>
<br> <br>
<h2>This is index.html</h2>
</div>
this is index.html with products.html fragment index.html
products.html
<body>
<div class="container">
<div th:fragment="content">
<h3>This is the fragment from products.html</h3>
<h2>List of products</h2>
<table class="table table-stripped">
<tr>
<th>Id</th>
<th>Description</th>
<th>Price</th>
<th>Image Url</th>
<th>List</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.id}"></td>
<td th:text="${product.description}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.imageUrl}"></td>
<td><a th:href="${'/products/numArt/' + product.numArt}">View</a></td>
<td><a>Edit</a></td>
<td><a>Delete</a></td>
</tr>
</table>
<div class="row">
<div class="col-sm-3">
<button>New Product</button>
</div>
</div>
</div>
</div>
this is products.html products.html
controller
@GetMapping("/products")
public String listProducts(Model model) {
System.out.println("Get all products...");
model.addAttribute("products", productRepository.findAll());
return "products";
}
解决方案
您在 products.html 中绑定products
对象而不是片段。所以制作另一种方法,如下所示。
@GetMapping("/products/fragment")
public ModelAndView listOfProducts() {
ModelAndView mv = new ModelAndView("index::custom-content");
mv.addObject("products", productRepository.findAll());
return mv;
}
并通过您的 index.html 中的 ajax 调用它。在索引文件中添加以下行
<script th:inline="javascript">
$(document).ready(function () {
loadData();
});
function loadData(){
$.ajax({
type: 'get',
url: /*[[ @{'/product/fragment'} ]]*/,
success: function(data){
$('.container').html(data);
},
async:false
})
}
</script>
<body>
<section >
<br> <br>
<div class="container">
<div th:fragment="custom-content">
<section th:replace="products :: content"></section>
<br> <br>
<h2>This is index.html</h2>
</div>
</div>
</section>....
希望这可以帮助。
推荐阅读
- javascript - 在提交表单之前如何等待 AJAX
- node.js - 如何将电子表格.values.batchUpdate 与 Google Cloud Functions 和 NodeJS 以及“googleapis”模块一起使用
- if-statement - 需要一个谷歌表格公式
- javascript - 如何在反应日期选择器中禁用日期和时间?
- ruby-on-rails - 为什么我的代码和 postgres 没有连接
- java - 用户必须先通过 Spring Security 进行身份验证,然后才能完成授权
- spring - 如何使用 Spring Webflux 限制请求有效负载大小?
- java - 在 web 视图中获取位置(更新)
- html - :checked 选项的工作方式与复选框的工作方式不同(内部代码)
- javascript - 如何将 aws 秘密管理器与 nodejs lambda 一起使用