gpt4 book ai didi

java - 我想使用 Spring Controller 中的 Iterable 在 JSP 文件中创建和填充列表项

转载 作者:行者123 更新时间:2023-12-01 22:05:13 25 4
gpt4 key购买 nike

我有以下 Controller ,我想将 MediaFile 对象的可变长度数组获取到 JSP 文件,以便我可以生成 html 列表。

package project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import project.MediaFileRepository;
import project.MediaFile;
import org.springframework.ui.Model;

@Controller
public class SearchController {

@Autowired
private MediaFileRepository repository;

@RequestMapping(value = "/searchmedia", method = RequestMethod.GET)
public String searchForm(Model model) {
// This is what I want to get to the JSP file
Iterable<MediaFile> mediaFiles = repository.findAll();

// I could also generate the html here and put that into the file
for (MediaFile mediaFile: repository.findAll()) {
model.addAttribute("mediaFile", mediaFile);
}

return "search";
}
}

我想在 jsp 文件中从长度为 N 的对象数组中获取类似的内容:

<ul>
<li>Info from Object 1 from array</li>
<li>Info from Object 2 from array</li>
.
.
.
<li>Info from Object N from array</li>
</ul>

我已经尝试解决这个问题一个小时了。有一件事是,这是一个小组项目,并且已决定不使用像百里香叶这样的模板引擎(尽管,根据这里的答案,我可能必须说服他们改变这一点)。

最佳答案

Iterable放入模型中:

model.addAttribute("mediaFiles", repository.findAll());

然后使用 JSTL 在 JSP 中循环:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<ul>
<c:forEach var="mediaFile" items="${mediaFiles}">
<li><c:out value="${mediaFile.name}"/></li>
</c:forEach>
</ul>
</body>
</html>

关于java - 我想使用 Spring Controller 中的 Iterable 在 JSP 文件中创建和填充列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32929483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com