玩框架IF语句和FOR循环

Play Framework IF statement and FOR loop

我是 MVC 的新手,正在关注 this link 我有一个使用 Solr 生成的 pdf 元数据的搜索页面。我的 if 语句和 html 端的 for 循环不起作用

Searching.java 在模型文件夹中:

public class Searching {

    public String q;

    public String outputTitle;
    public String outputAuthor;
    public String outputContent;
    public String outputPage;
    public String outputPath;

}

Application.java 中的搜索功能:

    final static Form<Searching> searchForm = form(Searching.class);
    final static List<Searching> searchList = new ArrayList<Searching>(); 

public static Result search() {
Form<Searching> filledForm = searchForm.bindFromRequest();
        Searching searched = filledForm.get();

....(database connection lines)

QueryResponse response = solr.query(query);
SolrDocumentList results = response.getResults();
    if(results.isEmpty())
                System.out.println("SEARCH NOT FOUND");
    else {
        for (int i = 0; i < results.size(); ++i) {

            searched.outputTitle = (String)results.get(i).getFirstValue("title");
            searched.outputAuthor = (String)results.get(i).getFirstValue("author");
            searched.outputPage =results.get(i).getFirstValue("pageNumber").toString();
            searched.outputContent = (String)results.get(i).getFirstValue("content");
            searched.outputPath =  (String)results.get(i).getFirstValue("path");    
            searchList.add(searched);   
        }
        System.out.println("\nresults.getNumFound(): "+ searched.outputFound);
        System.out.println("results.size(): "+results.size());
        }
    return play.mvc.Results.ok(search.render(searched, searchForm, searchList)); 
    }

search.scala.html

@(searched: Searching, searchForm: Form[Searching], searchList: List[Searching])
.. some buttons,a search bar...
@if(searchList.isEmpty()) {
                <h1>Error</h1>
            } else {
                @for(search <- searchList) {
                <ul>Title: @search.outputTitle</ul> 
                <ul>Author: @search.outputAuthor <a href="@search.outputPath" download>Download PDF</a></ul>
                <ul>Number of Page(s): @search.outputPage</ul>
                }   
            }

Java 代码运行良好。我可以在终端上看到输出,但我的 html 端有问题,它根据 searchList

的大小多次显示一本书

我明确地发布了答案,即使我能够在聊天中帮助 OP - 也许其他人 运行 遇到了这样的问题但没有检查聊天:

问题是即使您在 for 循环中有该行,您仍在使用相同的 searched 变量。您要做的是在进入循环时重新初始化变量。类似于:

for (...) {
    searched = new Searching();
    searched.outputTitle = (String)results.get(i).getFirstValue("title");
    ....
    searchList.add(searched);
}

这解决了重复问题,现在一切都很好。