我正在尝试在我的网站上使用 th:each 函数来查找数据库中的所有狗,并使用以下代码。在我的 Controller 中,我有:
@Controller
public class DogController {
private DogDatabase database = new DogDatabase();
@RequestMapping(value = "/allDogs", method = RequestMethod.GET)
public String getAllDogs(Model model)
{
ArrayList<Integer> ids = database.getAllIDs();
System.out.println(ids.size());
Dog[] dogs = new Dog[ids.size()+1];
for(int i = 0; i < ids.size(); ++i)
{
dogs[i] = database.getDog(ids.get(i));
}
model.addAttribute("dogs", dogs);
return "getAllDogs";
}
在这个 for 循环之后,我对数组中的每个对象执行了 println 并验证了我的所有狗对象都是有效的且不为空。验证数组正确后,我将其作为模型传递并尝试将其放入 html 中。当前的问题是,当我转到 html 时,它什么也不显示。我没有收到任何 thymeleaf 错误,只是出现空白屏幕。附件是我的 html 代码,我在其中调用 th:each
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>All Dogs</title>
</head>
<body>
<table>
<th:block th:each="dog : ${dogs}">
<tr>
<td>Name: </td>
<td th:text="${dog.name}">Name</td>
</tr>
</th:block>
</table>
</body>
</html>
编辑一和二:编辑是为了修复错误,这不在我的代码中
编辑三:我尝试在迭代器中切换狗和狗(如上面的代码所示),但现在我收到一个错误,指出存在“评估 SpringEL 表达式的异常:“dog.name”(模板:“getAllDogs”) - 第 13 行,第 21 栏)"
然而,这没有意义,因为我在整个网站中使用dog.name,并且getName()在Dog类中是公共(public)的。根据要求,我添加了我的狗类:https://pastebin.com/Lknc8dtZ
最佳答案
我相信问题出在这里:
<th:block th:each="dogs : ${dog}">
在 Controller 中,您将 Dog[] 数组绑定(bind)到变量“dogs”:
model.addAttribute("dogs", dogs);
所以在你的模板中你应该像这样迭代:
<th:block th:each="dog : ${dogs}">
<tr>
<td>Name: </td>
<td th:text="${dog.name}">Name</td>
</tr>
</th:block>
寻找狗数组中的每只狗:)
关于java - thymeleaf :each repair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53507056/