java - thymeleaf 获得前 3 个对象

标签 java spring spring-mvc spring-boot thymeleaf

你能帮帮我吗? 我想展示我的前 3 个产品对象,我不知道它必须如何。 我尝试使用 thymeleaf 序列,但它不起作用。也许有人可以提示我如何做到这一点。

HTML:

<th:block th:each="product:${products}">

<a  th:class="production_Page" th:href="@{'product/'+${product.id}}"> <p 
th:text="${product.productName}"/></a>

<a th:class="production_Page" 
th:href="@{'productDelete/'+${product.id}}">Delete</a>

<a th:class="production_Page" 
th:href="@{'productEdit/'+${product.id}}">Edit</a>

<img  th:class="productImage" th:src="${product.pathImage}"/>
<br/>
</th:block>

Controller :

@GetMapping("/products")
public String seeAllProductsIntoAList(Model model){
    model.addAttribute("products", productService.findAll());
    model.addAttribute("categories", categoryService.findAll());
    return "/productView/products";
}

如果有人能就此问题提示我,那就太好了。

谢谢。

最佳答案

由于 productsProduct 的列表,您必须遍历该列表。在 thymeleaf 上,您可以使用 th:each 属性进行迭代。因此,对于您的情况,您可以使用以下内容。试一试。

<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">

我不完全确定,但根据您的问题,您只需要前三个对象。为此,您可以使用 th:each 中定义的状态变量。更多细节你可以找到here .

关于java - thymeleaf 获得前 3 个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526117/

相关文章:

java - 作为变量传递时,Thymeleaf 片段无法解析,即 <div th :replace ="${page}">

java - 如何在 Jquery 中使用 modelAttribute 值作为选择框

java - 使用 JMS 进行简单聊天

java - Java 小程序可以打开 "select directory"并通过 JavaScript 交互写入文件系统吗?

java - KafkaMessageListenerContainer 与 ConcurrentMessageListenerContainer

java - 带有嵌套 Java 和 Xml Spring 配置的 JUnit

java - Spring 5 样板项目无法运行

java - 如何在不由 spring 容器维护的类中 Autowiring 成员变量?

java - RxJava : what is difference between callbacks in doOnError ('callback' ) and subscribe(*, 'callback')

java - 如果 exe 路径包含非英文字符,则使用 Runtime.getRuntime().exec 方法调用 exe 时出错